Counter for items in lists in lists?
Steven Bethard
steven.bethard at gmail.com
Sat Sep 25 03:09:06 EDT 2004
Bryan <belred1 <at> yahoo.com> writes:
> 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}
Yeah, if that's the case, you don't really even need to construct a temporary
list:
>>> myList=[['a','b','c','d'],['a','f','g','h'],['a','b','x','y']]
>>> counts = {}
>>> for lst in myList:
... for item in lst:
... counts[item] = counts.get(item, 0) + 1
...
>>> counts
{'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