问题
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