这个问题在这里已有答案:
任务:第一行包含整数N.接下来的N行包含一个单词。输出应为:1)在第一行,输出输入中不同单词的数量。 2)在第二行,根据输入中的外观输出每个不同单词的出现次数。我对#1没有任何困难。对于第2点,我使用Counter来获取单词的出现次数。但是我很难按收到的顺序打印它们。以下是我的代码。
from collections import Counter
from collections import OrderedDict
all_words=[]
for _ in range(int(raw_input())):
name=raw_input()
all_words.append(name)
uniqlst=list(set(all_words))
print len(uniqlst)##On the first line, output the number of distinct words from the input.
x=OrderedDict(Counter(all_words)) #This is where I am having trouble to get values of x in the order it was received.
print " ".join(map(str,x.values()))
输入:
4
bcdef
abcdef
bcde
bcdef
输出我的代码:
3
1 1 2
预期产量:
3
2 1 1
这不起作用:
x=OrderedDict(Counter(all_words))
首先,你通过迭代Counter
创建一个all_words
。由于Counter
只是一个引人注目的dict
,根据你的Python版本,这可能是插入顺序,一致但任意的顺序,或明确随机的顺序。
然后你通过迭代OrderedDict
创建一个Counter
。这将保留Counter
的顺序 - 如果Counter
处于任意顺序,这不是非常有用。
你想要做的是创建一个类,它执行Counter
所做的一切,但也做OrderedDict
所做的一切。这是微不足道的:
class OrderedCounter(Counter, OrderedDict):
'Counter that remembers the order elements are first encountered'
这不是很完美,因为它的repr
会给你错误的类名,并且它不会正确的腌制。但修复这几乎就是这么简单。事实上,这是given as an example in the docs:
class OrderedCounter(Counter, OrderedDict):
'Counter that remembers the order elements are first encountered'
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))
def __reduce__(self):
return self.__class__, (OrderedDict(self),)