Counter for items in lists in lists?

Steven Bethard steven.bethard at gmail.com
Sat Sep 25 02:34:54 EDT 2004


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




More information about the Python-list mailing list