Python-counting Element Frequency In A 2d List
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',
Solution 1:
Assuming I understand what you want,
>>> collections.Counter([x forsublistin a forxin 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})
Solution 2:
You can use a defaultdict
:
from collections importdefaultdictd= defaultdict(int)
for sublist in a:
for word in sublist:
d[word] += 1
Solution 3:
You already know about list.count()
. Simply get the count of word in each sublist
and sum
them. For example:
>>>my_word = 'its'>>>sum(sublist.count(my_word) for sublist in a)
2
In case you want the frequency of every word present in your list
, there are many good answers available here for that. Alternatively, in case you want to do it without any import
(using normal dict
), you may do:
my_dict= {}
for sublist in a:for item in sublist:if item not in my_dict:my_dict[item]=0my_dict[item]+=1# Value of my_dict:
{'friends':1, 'is':1, 'it':1, 'its':2, 'mrpycharm':3, 'hello':1}
Post a Comment for "Python-counting Element Frequency In A 2d List"