首页 > 解决方案 > 如何在列表中找到最常用的单词?

问题描述

我刚刚开始编码;所以我没有使用字典或集合或导入或任何比 for/while 循环和 if 语句更高级的东西

list1 = ["cry", "me", "me", "no", "me", "no", "no", "cry", "me"] 
list2 = ["cry", "cry", "cry", "no", "no", "no", "me", "me", "me"] 

def codedlist(number):
      max= 0
      for k in hello:
            if first.count(number) > max:
                    max= first.count(number)

标签: pythonlist

解决方案


您可以使用collections.Counter 单线查找它:

from collections import Counter

list1 = ["cry", "me", "me", "no", "me", "no", "no", "cry", "me"] 
Counter(list1).most_common()[-1]

输出:

('cry', 2)

(most_common() 返回按计数排序的计数元素列表,最后一个元素 [-1] 是最少计数)

如果你可以有几个最小的元素,或者更复杂一点:

from collections import Counter

list1 = [1,2,3,4,4,4,4,4]
counted = Counter(list1).most_common()
least_count = min(counted, key=lambda y: y[1])[1]
list(filter(lambda x: x[1] == least_count, counted))

输出:

[(1, 1), (2, 1), (3, 1)]


推荐阅读