Reputation: 20136
Let's say I have a Counter
object: Counter({'test': 2, 'this': 1, 'is': 1})
I would like to iterate over this object in the following way:
c = Counter({'test': 2, 'this': 1, 'is': 1})
for i,s in my_counter_iterator(c):
print i, ":", s
>> 1 : ['this', 'is']
>> 2 : ['test']
How do I do that efficiently (this code should run on a web server for each request...)?
EDIT
I have tried this, but I have the feeling there are more efficient ways. Are there?
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']
Upvotes: 2
Views: 6568
Reputation: 363817
If you want to do this with large Counter
s, you really have no choice but to invert the mapping.
inv_c = defaultdict(list)
for k, v in c.iteritems():
inv_c[v].append(k)
Then inv_c.iteritems()
is what you want.
Upvotes: 6