Python:如何允许一组中的重复项?

编程入门 行业动态 更新时间:2024-10-27 18:22:36
本文介绍了Python:如何允许一组中的重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是适当的示例代码块:

letters = set(str(raw_input(Type letters:)))

正如你所看到的,关键是要写一些字母分配给字母供以后使用。但是如果我输入aaabbcdd,则输出letter返回

set(['a','c' 'b','d'])

我的问题是如何编写代码,输出将允许这样的重复:

set(['a','a','a','b' 'b','c','d','d'])

? >

解决方案

设置不存储重复项,这就是为什么它被称为设置。您应该使用普通的 str 或列表,如有必要,进行排序。

>>> sort(raw_input(Type letters:))键入字母:foobar ['a','b','f','o','o','r']

另一种替代方法(但您的示例为过分)是多集群容器 collections.Counter ,可从Python 2.7。 / p>

>>>从集合导入计数器>>>> c = Counter(raw_input(Type letters:))>>> c 计数器({'o':2,'a':1,'r':1,'b':1,'f':1})>>>排序(c.elements()) ['a','b','f','o','o','r'] pre>

I ran into a problem regarding set in Python 2.7.

Here's the appropriate example code block:

letters = set(str(raw_input("Type letters: ")))

As you can see, the point is to write some letters to assign to "letters" for later use. But if I type "aaabbcdd", the output of "letters" returns

set(['a', 'c', 'b', 'd'])

My question is how to write the code, so that the output will allow duplicates like this:

set(['a','a','a','b','b','c','d','d'])

?

解决方案

set doesn't store duplicates, which is why it's called a set. You should use an ordinary str or list and sort it if necessary.

>>> sorted(raw_input("Type letters: ")) Type letters: foobar ['a', 'b', 'f', 'o', 'o', 'r']

An alternative (but overkill for your example) is the multiset container collections.Counter, available from Python 2.7.

>>> from collections import Counter >>> c = Counter(raw_input("Type letters: ")) >>> c Counter({'o': 2, 'a': 1, 'r': 1, 'b': 1, 'f': 1}) >>> sorted(c.elements()) ['a', 'b', 'f', 'o', 'o', 'r']

更多推荐

Python:如何允许一组中的重复项?

本文发布于:2023-11-10 03:20:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574214.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!