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  /  [EMAIL PROTECTED]  /  http://blog.ianbicking.org
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to