【发布时间】:2019-02-09 21:53:52
【问题描述】:
任务: 第一行包含整数 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
【问题讨论】:
-
在映射和加入之前反转列表。
-
Counter以任意顺序为您提供值。OrderedDict然后保留该任意顺序。这不是很有帮助。您需要做的是创建一个OrderedCounter,即a trivial example in thecollectionsdocs。 -
@Bazingaa 我没有使用 set 来获取 x 的值。