我有一个看起来像这样的列表:
co_list = [[387, 875, 125, 822], [397, 994, 135, 941], [397, 994, 135, 941], [397, 994, 135, 941], [397, 994, 135, 941], [1766, 696, 1504, 643]. . . ]
我需要计算相同坐标列表的数量并返回计数,在本例中为 4。
到目前为止我已经尝试过:
def most_common(lst):
lst = list(lst)
return max(set(lst), key=lst.count)
for each in kk :
print most_common(each)
使用它我可以得到每个列表中出现次数最多的元素。 但我的目的是获取出现次数超过 3 次的列表。
预期输出:
(element, count) = ([397, 994, 135, 941], 4)
如有任何帮助,我们将不胜感激。谢谢。
最佳答案
您可以使用collections.Counter
对于该任务:
from collections import Counter
co_list = [[387, 875, 125, 822], [397, 994, 135, 941], [397, 994, 135, 941], [397, 994, 135, 941], [397, 994, 135, 941], [1766, 696, 1504, 643]]
common_list, appearances = Counter([tuple(x) for x in co_list]).most_common(1)[0] # Note 1
if appearances > 3:
print((list(common_list), appearances)) # ([397, 994, 135, 941], 4)
else:
print('No list appears more than 3 times!')
1) 内部 list
被转换为 tuple
,因为 Counter
构建了 dict
和 >不可散列的列表
不能用作键
。
关于python - 计算Python中列表列表中列表的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45757882/