1

假设我有一个Counter对象:Counter({'test': 2, 'this': 1, 'is': 1})

我想通过以下方式迭代这个对象:

c = Counter({'test': 2, 'this': 1, 'is': 1})

for i,s in my_counter_iterator(c):
    print i, ":", s

>> 1 : ['this', 'is']
>> 2 : ['test']

我如何有效地做到这一点(此代码应针对每个请求在 Web 服务器上运行......)?

编辑

我已经尝试过了,但我觉得有更有效的方法。在那里?

from itertools import groupby

for k,g in groupby(sorted(c.keys(), key=lambda x: c[x]),key=lambda x: c[x]):
    print k, list(g)


1 ['this', 'is']
2 ['test']
4

1 回答 1

5

如果你想用大的s来做这个Counter,你真的别无选择,只能反转映射。

inv_c = defaultdict(list)
for k, v in c.iteritems():
    inv_c[v].append(k)

然后inv_c.iteritems()就是你想要的。

于 2012-11-14T13:55:06.403 回答