Reputation: 137
I have 3 lists with all unique elements in each and I want to count the number of occurrence for each element. Unique here means all the elements in a list are unique, no duplicated ones.
An example of the data:
list(c[0]): list(c[1]): list(c[1]):
a a a
b b b
c c
d
And so the desired output should be
a:3,b:3,c:2,d:1
I understand that Counter
can be applied to within one list, but how do I calculate across lists?
Upvotes: 1
Views: 78
Reputation: 12015
Use chain.from_iterable
to convert the list to a flat list and then feed it to Counter
from collections import Counter
from itertools import chain
c = [['a', 'b', 'c', 'd'], ['a', 'b'], ['a']]
Counter(chain.from_iterable(c))
# Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1})
Upvotes: 0
Reputation: 106553
Merge the 3 lists with itertools.chain
and then use collections.Counter
to count the items.
from collections import Counter
from itertools import chain
c = [['a', 'b', 'c', 'd'], ['a', 'b'], ['a']]
print(dict(Counter(chain(*c))))
This outputs:
{'a': 3, 'b': 2, 'c': 1, 'd': 1}
Upvotes: 0
Reputation: 13498
Flatten the list and then use counter:
Assuming lst is a list of the three lists in question:
flat = [i for sub in lst for i in sub]
Counter(flat)
Upvotes: 3