[Python-Dev] tally (and other accumulators) (original) (raw)
Georg Brandl g.brandl at gmx.net
Tue Apr 4 19:35:50 CEST 2006
- Previous message: [Python-Dev] tally (and other accumulators)
- Next message: [Python-Dev] tally (and other accumulators)
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Alex Martelli wrote:
On Apr 4, 2006, at 8:01 AM, Jeremy Hylton wrote:
On 4/4/06, Alex Martelli <aleaxit at gmail.com> wrote: import collections def tally(seq): d = collections.defaultdict(int) for item in seq: d[item] += 1 return dict(d) ... Putting it somewhere in collections seems like a great idea. defaultdict is a bit odd, because the functionality doesn't have anything to do with defaults, just dicts. maybe a classmethod on regular dicts would make more sense? Good points: it should probably be a classmethod on dict, or a function in module collections. I write this function regularly, so I'd be happy to have it available directly. Heh, same here -- soon as I saw it proposed on c.l.py I recognized an old friend and it struck me that, simple but widely used, it should be somewhere in the standard library.
Why not make it collections.bag, like the following:
class bag(dict): def init(self, iterable=None): dict.init(self) if iterable: self.update(iterable)
def update(self, iterable):
for item in iterable:
self.add(item)
def add(self, item):
self[item] = self.get(item, 0) + 1
def remove(self, item):
if self[item] == 1:
del self[item]
else:
self[item] -= 1
def count(self, item):
return self[item]
(etc.)
Georg
- Previous message: [Python-Dev] tally (and other accumulators)
- Next message: [Python-Dev] tally (and other accumulators)
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]