Johnny Chiu
Johnny Chiu

Reputation: 469

count number of show up in another list

I have 2 lists total and word.

total=[['a','a','b','b','b'],['a','c']]
word=['a','b']

I want to use list comprehension to output the number of times each of the words that show up in total appear.

For example:

output = {'a': 2, 'b': 1}      

Upvotes: 0

Views: 45

Answers (2)

mad_
mad_

Reputation: 8273

May be this

from collections import Counter
from itertools import chain
total=[['a','a','b','b','b'],['a','c']]
total=[set(i) for i in total]
word=['a','b']
{k:v for k,v in Counter(chain(*total)).items() if k in word}

Upvotes: 0

fuglede
fuglede

Reputation: 18201

You could use the dictionary comprehension

{w: sum(w in l for l in total) for w in word}

Upvotes: 2

Related Questions