0

My goal is to count frequency of words in a list of list. So, I have:

list_1 = [['x', 'y', 'z'], ['x', 'y', 'w'], ['w', 'x', 'y']]

My goal is something like:

x:3, y:3, w:2, z:1
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Victor Castro
  • 105
  • 1
  • 6

2 Answers2

3

You can use Counter:

>>> from collections import Counter
>>> Counter(elem for sub in list_1 for elem in sub)
Counter({'x': 3, 'y': 3, 'w': 2, 'z': 1})
Francisco
  • 10,918
  • 6
  • 34
  • 45
1

You can do it like this:

list_1 = [['x', 'y', 'z'], ['x', 'y', 'w'], ['w', 'x', 'y']]

freq = {}

for i in list_1:
    for j in i:
        try:
            freq[j] += 1
        except KeyError:
            freq[j] = 1
        
print(freq)
Marko Borković
  • 1,884
  • 1
  • 7
  • 22