使用计数器创建列表中特定单词的字典

Using counter to create dict of specifc words in the list

我有一个列表,如下所示:

my_list = ['singapore','india','united states','london','paris','india','london','china','singapore','singapore','new york']

现在我想要 Counter[dict] 此列表中的特定单词

Counter(my_list) gives me the following :
Counter({'singapore': 3, 'india': 2, 'london': 2, 'united states': 1, 'paris': 1, 'china': 1, 'new york': 1})

但是有没有一种方法可以创建一个仅包含列表中特定单词的计数器,例如 ['london','india','singapore']

中的单词计数器

最快的方法是什么?我的名单很大。

我尝试了什么:例如 my_list.count('london')。但是有没有更快的方法来实现这一点?

您可以使用集合来过滤单词,例如:

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)

输出

Counter({'singapore': 3, 'india': 2, 'london': 2})