Python: How to allow duplicates in a set?

萝らか妹 提交于 2019-12-10 13:16:56

问题


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'])

?


回答1:


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']



回答2:


A set does not allow duplicates by definition. Use a simple list.

In your case:

letters = list(str(raw_input("Type letters: ")))
print sorted(letters)


来源:https://stackoverflow.com/questions/9455750/python-how-to-allow-duplicates-in-a-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!