Pythonic方法以递减的顺序迭代collections.Counter()实例?

Ina*_*ist 30 python iteration collections python-2.7

在Python 2(2.7,更准确地说)中,我想以递减计数顺序迭代collections.Counter实例.

>>> import collections
>>> c = collections.Counter()
>>> c['a'] = 1
>>> c['b'] = 999
>>> c
Counter({'b': 999, 'a': 1})
>>> for x in c:
        print x
a
b
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,似乎元素按照它们添加到Counter实例的顺序进行迭代.

我想从最高到最低迭代列表.我看到Counter的字符串表示就是这样,只是想知道是否有推荐的方法来做到这一点.

Sve*_*ach 39

您可以迭代c.most_common()以获得所需顺序的项目.另见文档Counter.most_common().

例:

>>> c = collections.Counter(a=1, b=999)
>>> c.most_common()
[('b', 999), ('a', 1)]
Run Code Online (Sandbox Code Playgroud)


dre*_*676 9

您的问题已通过仅返回降序解决,但这里是一般如何做到这一点。万一其他人从谷歌来到这里,我必须解决这个问题。基本上你上面的内容返回了 collections.Counter() 中字典的键。要获取值,您只需要将键传回字典,如下所示:

for x in c:
    key = x
    value = c[key]
Run Code Online (Sandbox Code Playgroud)

我有一个更具体的问题,我有字数统计并想过滤掉低频的问题。这里的技巧是制作 collections.Counter() 的副本,否则当您尝试从字典中删除它们时,您将收到“RuntimeError:在迭代期间字典更改了大小”。

for word in words.copy():
    # remove small instance words
    if words[word] <= 3:
        del words[word]
Run Code Online (Sandbox Code Playgroud)


Cha*_*dra 5

这是在Python集合中迭代Counter的示例:

>>>def counterIterator(): 
 import collections
 counter = collections.Counter()
 counter.update(('u1','u1'))
 counter.update(('u2','u2'))
 counter.update(('u2','u1'))
 for ele in counter:
  print(ele,counter[ele])
>>>counterIterator()
u1 3
u2 3
Run Code Online (Sandbox Code Playgroud)