如何按接收计数器对象的顺序获取其值?

2024-03-29 10:56:47 发布

您现在位置:Python中文网/ 问答频道 /正文

任务: 第一行包含整数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

Tags: the代码nameinfromimportinputraw
1条回答
网友
1楼 · 发布于 2024-03-29 10:56:47

这是行不通的:

x=OrderedDict(Counter(all_words))

首先,通过迭代all_words创建一个Counter。由于Counter只是一个隐藏的dict,这取决于您的Python版本,它可以是插入顺序、一致但任意的顺序或显式随机顺序。你知道吗

然后通过迭代Counter创建一个OrderedDict。这将保持Counter的顺序—如果Counter的顺序是任意的,那么这就不太有用了。你知道吗

您要做的是创建一个类,它执行Counter所做的一切,但也执行OrderedDict所做的一切。这是微不足道的:

class OrderedCounter(Counter, OrderedDict):
    'Counter that remembers the order elements are first encountered'

这并不是很完美,因为它的repr会给你错误的类名,而且它不会正确地pickle。但解决这个问题几乎同样简单。事实上,它是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),)

相关问题 更多 >