Python-Counting element frequency in a 2D list

python

Solution

Assuming I understand what you want,

>>> collections.Counter([x for sublist in a for x in sublist])
Counter({'mrpycharm': 3, 'its': 2, 'friends': 1, 'is': 1, 'it': 1, 'hello': 1})

Or,

>>> c = collections.Counter()
>>> for sublist in a:
...     c.update(sublist)
...
>>> c
Counter({'mrpycharm': 3, 'its': 2, 'friends': 1, 'is': 1, 'it': 1, 'hello': 1})

Problem

I want to know if there is a way to count element frequencies in a 2D python list. For 1D lists, we can use ``` list.count(word) ``` but what if I have a list: ``` a = [ ['hello', 'friends', 'its', 'mrpycharm'], ['mrpycharm', 'it', 'is'], ['its', 'mrpycharm'] ] ``` can i find the frequency for each word in this 2D list?

Original source

Related problems