Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 625
indecisivecoder Avatar asked Oct 06 '13 16:10

indecisivecoder


People also ask

Can you use counter on a list?

A counter can be used on a string, list, dictionary, and tuple.

How do you count the number of lists within a list in Python?

The most straightforward way to get the number of elements in a list is to use the Python built-in function len() . As the name function suggests, len() returns the length of the list, regardless of the types of elements in it.


2 Answers

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})
like image 123
falsetru Avatar answered Oct 22 '22 02:10

falsetru


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)
like image 27
Iqra. Avatar answered Oct 22 '22 00:10

Iqra.