Python 使用计数器创建列表中特定单词的dict

Python 使用计数器创建列表中特定单词的dict,python,python-3.x,counter,Python,Python 3.x,Counter,我有一个如下列表: my_list = ['singapore','india','united states','london','paris','india','london','china','singapore','singapore','new york'] 现在我想要一个只包含列表中特定单词的计数器[dict] Counter(my_list) gives me the following : Counter({'singapore': 3, 'india': 2, 'london

我有一个如下列表:

my_list = ['singapore','india','united states','london','paris','india','london','china','singapore','singapore','new york']
现在我想要一个只包含列表中特定单词的计数器[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})
但是有没有一种方法可以从列表中创建一个只包含特定单词的计数器,例如[‘伦敦’、‘印度’、‘新加坡’中的单词计数器]

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


我试过的:我的清单。例如,数“伦敦”。但是有没有更快的方法来实现这一点呢?

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

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)
输出


我喜欢这样的类比,将值更改为针将是非常棒的lol@Daniel谢谢你,你知道这比不使用任何基准测试的情况下使用count更快吗?@RameshK只需1个字,count就会更快,对于多个单词来说,这种方法更快。我有点担心你们并没有在大海捞针的时候使用反针。这让我非常不安。看看你是否觉得这有帮助
Counter({'singapore': 3, 'india': 2, 'london': 2})