【问题标题】:Using counter to create dict of specifc words in the list使用计数器创建列表中特定单词的字典
【发布时间】:2019-09-26 18:13:36
【问题描述】:

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

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')。但是有没有更快的方法来实现这一点?

【问题讨论】:

标签: python python-3.x counter


【解决方案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)

输出

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

【讨论】:

  • 我喜欢这个类比,将value 更改为needle 哈哈
  • @Daniel 谢谢你,你知道这是否比在没有任何基准的情况下使用 count 更快吗?
  • @RameshK 对于只有 1 个单词,计数会更快,对于多个单词,这种方法更快。
  • 我有点担心你没有使用Counter(needle for needle in haystack if needle in needles)。这让我深感不安。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-19
  • 2018-06-13
  • 1970-01-01
  • 2022-11-18
  • 2021-02-22
  • 1970-01-01
相关资源
最近更新 更多