3 ms·
You mentioned it a bit, but I want to make it clear that, even if you don't use 2.7, you can still count by doing: from collections import defaultdict
by elbear 14y ago
You mentioned it a bit, but I want to make it clear that, even if you don't use 2.7, you can still count by doing:
from collections import defaultdict
counter = defaultdict(int)
There is a difference though, because you have to count manually, i.e:
for i in 'supercalifragilisticexpialidocius':
counter[i] += 1
Also, because defaultdict accepts any callable, you can have a dict of counters by doing:
counters = defaultdict(lambda: defaultdict(int))
for word in ['apple', 'berry', 'grape']:
for letter in word:
counters[word][letter] += 1
This is not very obvious, so I don't use it a lot, but sometimes it's the most elegant solution.
- icebraining 14y agoThere's also an implementation of Counter for 2.5+ on ActiveState: http://code.activestate.com/recipes/576611-counter-class/ http://code.activestate.com/recipes/576611-counter-class/
- ciupicri 14y agoFor Python 2.7 there's collections.Counter [1]: import collections c = collections.Counter('supercalifragilisticexpialidocius') print c # Counter({'i': 7, 'a': 3, 'c': 3, 'l': 3, 's': 3, 'e': 2, # 'p': 2, 'r': 2, 'u': 2, 'd': 1, 'g': 1, 'f': 1, # 'o': 1, 't': 1, 'x': 1}) [1] http://docs.python.org/2.7/library/collections.html#collections.Counter http://docs.python.org/2.7/library/collections.html#collecti...
- andreasvc 14y agoIt's odd that with all the 'high-brow' datatype names such as dictionaries, tuples, and sets, they decided to call this one Counter instead of the obvious choice 'multiset' (or 'bag'); it supports set operations such as intersection, so it's more generally useful than just collecting top ten lists &c.
- deleted 14y ago[deleted]