任务: 第一行包含整数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
这是行不通的:
首先,通过迭代
all_words
创建一个Counter
。由于Counter
只是一个隐藏的dict
,这取决于您的Python版本,它可以是插入顺序、一致但任意的顺序或显式随机顺序。你知道吗然后通过迭代
Counter
创建一个OrderedDict
。这将保持Counter
的顺序—如果Counter
的顺序是任意的,那么这就不太有用了。你知道吗您要做的是创建一个类,它执行
Counter
所做的一切,但也执行OrderedDict
所做的一切。这是微不足道的:这并不是很完美,因为它的
repr
会给你错误的类名,而且它不会正确地pickle。但解决这个问题几乎同样简单。事实上,它是given as an example in the docs:相关问题 更多 >
编程相关推荐