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'])
?
Python set doesn't have duplicate elements. We can use the built-in set() function to convert the list to a set, then use the list() function to convert it back to the list.
You can't. That's the point of Set. Sets, by their mathematical definition, can't have duplicates.
Why set does not allowed duplicates,How it will work internally. The meaning of "sets do not allow duplicate values" is that when you add a duplicate to a set, the duplicate is ignored, and the set remains unchanged.
Sets does not have repeated elements.
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']
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With