【问题标题】:How to get values of a Counter object in the order which it was received? [duplicate]如何按接收顺序获取 Counter 对象的值? [复制]
【发布时间】: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 the collections docs
  • @Bazingaa 我没有使用 set 来获取 x 的值。

标签: python ordereddictionary


【解决方案1】:

这是行不通的:

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 会给你错误的类名,它不会正确腌制。但修复它几乎一样简单。其实是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),)

【讨论】:

    猜你喜欢
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多