[Python-Dev] tally (and other accumulators)
Ian Bicking
ianb at colorstudy.com
Tue Apr 4 18:54:09 CEST 2006
Alex Martelli wrote:
> It's a bit late for 2.5, of course, but, I thought I'd propose it
> anyway -- I noticed it on c.l.py.
>
> In 2.3/2.4 we have many ways to generate and process iterators but
> few "accumulators" -- functions that accept an iterable and produce
> some kind of "summary result" from it. sum, min, max, for example.
> And any, all in 2.5.
>
> The proposed function tally accepts an iterable whose items are
> hashable and returns a dict mapping each item to its count (number of
> times it appears).
>
> This is quite general and simple at the same time: for example, it
> was proposed originally to answer some complaint about any and all
> giving no indication of the count of true/false items:
>
> tally(bool(x) for x in seq)
>
> would give a dict with two entries, counts of true and false items.
>
> Just like the other accumulators mentioned above, tally is simple to
> implement, especially with the new collections.defaultdict:
>
> import collections
> def tally(seq):
> d = collections.defaultdict(int)
> for item in seq:
> d[item] += 1
> return dict(d)
Or:
import collections
bag = collections.Bag([1, 2, 3, 2, 1])
assert bag.count(1) == 2
assert bag.count(0) == 0
assert 3 in bag
# etc...
--
Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org
More information about the Python-Dev
mailing list