Reputation: 1785
I have a list that looks like :
my_list = ['singapore','india','united states','london','paris','india','london','china','singapore','singapore','new york']
Now I want a Counter[dict]
of only specific words in this list
Counter(my_list) gives me the following :
Counter({'singapore': 3, 'india': 2, 'london': 2, 'united states': 1, 'paris': 1, 'china': 1, 'new york': 1})
But is there a way to create a Counter of only specific words from a list , like for example Counter of words in ['london','india','singapore']
What would be the fastest way to do this ? My list is very large.
What I tried : my_list.count('london')
for example. But is there a faster way to achieve this ?
Upvotes: 0
Views: 55
Reputation: 61910
You could use a set to filter the words, for example:
from collections import Counter
needles = {'london', 'india', 'singapore'}
haystack = ['singapore', 'india', 'united states', 'london', 'paris', 'india',
'london', 'china', 'singapore', 'singapore', 'new york']
result = Counter(value for value in haystack if value in needles)
print(result)
Output
Counter({'singapore': 3, 'india': 2, 'london': 2})
Upvotes: 8