'Using Counter with list of lists
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.
Solution 1:[1]
The following code snippet brings all the occurrences' count of the list's item, hope this will help.
from collections import Counter
_list = [['a', 'b', 'c', 'd', 'a'],['a', 'a', 'g', 'b', 'e', 'g'],['h', 'g', 't', 'y', 'u']]
words = Counter(c for clist in _list for c in clist)
print(words)
Solution 2:[2]
from itertools import chain
from collections import Counter
seq = [['a','b','a','c'], ['a','b','c','d']]
c = Counter(chain(*seq))
print(c)
Counter({'a': 3, 'b': 2, 'c': 2, 'd': 1})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Iqra. |
| Solution 2 |
