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
  • 107,083
  • 22
  • 201
  • 376
  • 2
    Please update your question with the code you have tried. – quamrana Jul 12 '21 at 17:47
  • Please take the [tour], read [what's on-topic here](/help/on-topic), [ask], and the [question checklist](//meta.stackoverflow.com/q/260648/843953), and provide a [mre]. "Implement this feature for me" is off-topic for this site. You have to _make an honest attempt_, and then ask a _specific question_ about your algorithm or technique. – Pranav Hosangadi Jul 12 '21 at 17:47

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,005
  • 5
  • 34
  • 42
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,568
  • 4
  • 21