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

标签 python

如果我有一个列表a,我想要一个函数f()

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

给出输出:

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

顺序也很重要,我需要它完全相似 我打算使用 Counter 但它不适用于列表。套装也不在话下。有没有比从头开始做整个事情更“简单”的方法,比如使用 Counter 之类的东西?

最佳答案

由于字典键不能有可变对象,您需要将它们转换为元组(不可变对象(immutable对象)),然后执行 Counter:

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

哪些输出:

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

关于python - 比较列表中的列表并计算出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56351927/

相关文章:

python - 如何将 SQLite3 数据库导入 Python Jupyter Notebook?

非矩形域上的 Python 3D 图

python - 我收到此错误 --> TypeError : string indices must be integers

python - Python 3.6 中的名称错误

python - 在遍历列表时附加到列表是否正确?

python - Pandas DataFrame 到字典列表

python mockito 参数捕获器

python - 如何获取有关函数的信息并调用它

c++ - python中具有静态成员的模板上的swig undefined symbol

python - python中的类变量重置