python - 计算Python中列表列表中列表的出现次数

标签 python list

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

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/

相关文章:

如果缺少,Python 将元素添加到列表中的列表

python - 总结嵌套字典列表的最简洁方法

java - 关于字谜的几个问题

python - 通过在列中重复范围来分隔 pandas df

python - 从matlab中直接在python中使用sklearn

java - java eclipse中的断点错误

python - 如何获得列表的旋转输出?

python - 将数字拆分为四舍五入的数字

Python:两个列表表达式

python - Django 时区 : feeling a bit confused