Python:如何允许一组中的重复项? [英] Python: How to allow duplicates in a set?

查看:204
本文介绍了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:如何允许一组中的重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆