在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
另外,在上述的例子中,看来该元件在它们被添加到反实例的顺序重复。
我想遍历列表从最高到最低。 我看到柜台的字符串表示这样做,只是想知道如果有一个推荐的方式来做到这一点。
可以遍历c.most_common()
来获得所需的顺序的项目。 另见的文档Counter.most_common()
例:
>>> c = collections.Counter(a=1, b=999)
>>> c.most_common()
[('b', 999), ('a', 1)]
下面是迭代在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
Your problem was solved for just returning descending order but here is how to do it generically. In case someone else comes here from Google here is how I had to solve it. Basically what you have above returns the keys for the dictionary inside collections.Counter(). To get the values you just need to pass the key back to the dictionary like so:
for x in c:
key = x
value = c[key]
I had a more specific problem where I had word counts and wanted to filter out the low frequency ones. The trick here is to make a copy of the collections.Counter() or you will get "RuntimeError: dictionary changed size during iteration" when you try to remove them from the dictionary.
for word in words.copy():
# remove small instance words
if words[word] <= 3:
del words[word]
文章来源: Pythonic way to iterate over a collections.Counter() instance in descending order?