按降序遍历collections.Counter()实例的Pythonic方法?

2024-04-30 05:00:54 发布

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

在Python2.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

在上面的示例中,元素似乎是按照添加到计数器实例的顺序进行迭代的。

我想从最高点到最低点遍历这个列表。我看到Counter的字符串表示可以做到这一点,只是想知道是否有推荐的方法可以做到这一点。


Tags: 实例inimport元素示例列表for顺序
3条回答

下面是在Python集合中迭代计数器的示例:

>>>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

你的问题已经解决了,只是返回降序,但这里是如何做它的一般性。万一有人从谷歌来这里,我就得解决这个问题。基本上,上面的内容返回collections.Counter()中字典的键。要获取值,只需像这样将密钥传递回字典:

for x in c:
    key = x
    value = c[key]

我有一个更具体的问题,我有字数,想过滤掉低频的。这里的诀窍是复制collections.Counter(),否则当您试图从字典中删除它们时,将得到“RuntimeError:dictionary changed size during iteration”。

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

您可以遍历c.most_common()以获得所需顺序的项。另请参见documentation of ^{}

示例:

>>> c = collections.Counter(a=1, b=999)
>>> c.most_common()
[('b', 999), ('a', 1)]

相关问题 更多 >