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')
例如。但是,有没有更快的方法来实现这一目标?
您可以使用集合来过滤单词,例如:
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)
归档时间: |
|
查看次数: |
39 次 |
最近记录: |