Counter for items in lists in lists?

Bryan belred1 at yahoo.com
Sat Sep 25 03:00:25 EDT 2004


Steven Bethard wrote:
> Charlotte Henkle <charlotte <at> fgm.com> writes:
> 
>>I'm pondering how to count the number of times an item appears in
>>total in a nested list.
> 
> 
> How about this:
> 
> 
>>>>myList=[['a','b','c','d'],['a','f','g','h'],['a','b','x','y']]
>>>>def count(item):
> 
> ...     if not isinstance(item, list):
> ...             return {item:1}
> ...     counts = {}
> ...     for i in item:
> ...             for key, ct in count(i).items():
> ...                     counts[key] = counts.get(key, 0) + ct
> ...     return counts
> ...
> 
>>>>count(myList)
> 
> {'a': 3, 'c': 1, 'b': 2, 'd': 1, 'g': 1, 'f': 1, 'h': 1, 'y': 1, 'x': 1}
> 
> Steve
> 

or maybe a less general approach might work if the nested list is always one deep:

 >>> myList=[['a','b','c','d'],['a','f','g','h'],['a','b','x','y']]
 >>> tmp = []
 >>> d = {}
 >>> for item in myList: tmp += item
 >>> for key in tmp: d[key] = d.get(key, 0) + 1
 >>> d
{'a': 3, 'c': 1, 'b': 2, 'd': 1, 'g': 1, 'f': 1, 'h': 1, 'y': 1, 'x': 1}


bryan



More information about the Python-list mailing list