python - 如何在列表中找到最常用的单词?
问题描述
我刚刚开始编码;所以我没有使用字典或集合或导入或任何比 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)
解决方案
您可以使用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)]
推荐阅读
- lua - 如何制作一个包含 100 个值但值不断增加的表格?
- javascript - 在 React 方法中设置状态
- python - 停止在美味派中重复相关对象
- javascript - 按名称 jQuery 的一部分选择元素
- r - 在 R 数据框中计算列中特定值范围的小计
- docker - Traeffic、Docker 和 Let's Encrypt
- node.js - 如何在 Beaglebone 上启动时运行 ReactJS 应用程序?
- android - 对齐文本(也就是说,使其适合文本视图并覆盖所有空间)
- python-3.x - 有没有一种保存方法来检索列表的索引而无需尝试捕获?
- firebase - 无法识别的请求类型:Request{com.google.android.gms.tasks.zzu@5843814