这是适当的示例代码块:
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:如何允许一组中的重复项?
发布评论