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

Ram*_*h K 0 python counter python-3.x

我有一个看起来像这样的列表:

my_list = ['singapore','india','united states','london','paris','india','london','china','singapore','singapore','new york']
Run Code Online (Sandbox Code Playgroud)

现在,我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})
Run Code Online (Sandbox Code Playgroud)

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

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

我试过的:my_list.count('london')例如。但是,有没有更快的方法来实现这一目标?

Dan*_*ejo 8

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

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)
Run Code Online (Sandbox Code Playgroud)

输出量

Counter({'singapore': 3, 'india': 2, 'london': 2})
Run Code Online (Sandbox Code Playgroud)

  • @RameshK对于仅1个单词,计数将更快,对于多个单词,此方法将更快。 (3认同)
  • 我喜欢这个比喻,很棒的是将“ value”更改为“ needle”大声笑 (2认同)
  • 我有点不高兴您没有使用Counter(如果在草堆里穿针,请在干草堆中穿针)。这让我深感不安。 (2认同)