Using Counter with list of lists

indecisivecoder picture indecisivecoder · Oct 6, 2013 · Viewed 8k times · Source

How would I use the Counter in the collections library to convert a list of lists into a count of the number of times each word occurs overall?

E.g. [['a','b','a','c'], ['a','b','c','d']] -> {a:2, b:2, c:2, d:1}

i.e. a,b and c occur in both lists but d only occurs in one list.

Answer

falsetru picture falsetru · Oct 6, 2013

Using generator expression with set:

>>> from collections import Counter
>>> seq = [['a','b','a','c'], ['a','b','c','d']]
>>> Counter(x for xs in seq for x in set(xs))
Counter({'a': 2, 'c': 2, 'b': 2, 'd': 1})

Responding to the comment, Without generator expression:

>>> c = Counter()
>>> for xs in seq:
...     for x in set(xs):
...         c[x] += 1
...
>>> c
Counter({'a': 2, 'c': 2, 'b': 2, 'd': 1})