[英]Try to find the number of times an item appears in another list of list of string
[英]How to find the maximum number of times that the most common item in a list appears?
我想查找列表中最常見的元素出現的次數。 例如:
[0,0,1,2,3,0] = 3
[0,2,1,1] = 2
[0,2,1,1,0] = 2
在Python中最有效的方法是什么?
您可以使用collections.Counter
的most_common
函數,如下所示
from collections import Counter
print Counter([0, 0, 1, 2, 3, 0]).most_common(1)
# [(0, 3)]
這為您提供了迭代中最常出現的項目。 如果只需要計數,可以使用max
函數,如下所示
print max(Counter([0, 0, 1, 2, 3, 0]).itervalues())
如果您使用的是Python 3.x,則
print(max(Counter([0, 0, 1, 2, 3, 0]).values()))
替代;
a_list = [0,2,1,1]
a_list.count(max(a_list, key=a_list.count))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.