简体   繁体   English

比较列表中的列表并计算出现次数

[英]Comparing lists within lists and counting occurrences

If I have a list of lists a , I want a function f() 如果我有一个列表a ,我想要一个函数f()

a = [[1,2,3],[1,2,3],[0,5,6],[0,5,4]]

that gives the output: 给出输出:

out = f(a)
out
>> {[1,2,3]:2,[0,5,6]:1,[0,5,4]:1]}

The order matters too, I need it to be completely similar I was going to use Counter but it does not work with lists. 顺序也很重要,我需要它与我要使用Counter完全相似,但不适用于列表。 Sets are also out of the question. 设置也不可行。 Is there some sort of 'easier' method than doing the whole thing from scratch maybe using something like Counter ? 是否有某种“更轻松”的方法,而不是像使用Counter这样从头开始做整个事情?

Since dictionary keys can't have mutable objects, you would need to convert them to a tuple (a immutable object), then do Counter : 由于字典键不能包含可变对象,因此您需要将其转换为元组(不可变对象),然后执行Counter

from collections import Counter
a = [[1,2,3],[1,2,3],[0,5,6],[0,5,4]]
print(Counter(map(tuple, a)))

Which outputs: 哪个输出:

Counter({(1, 2, 3): 2, (0, 5, 6): 1, (0, 5, 4): 1})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM