Python:计算列表中列表元素的出现次数

标签 python list count

我正在尝试计算列表中元素出现的次数,如果这些元素也是列表的话。顺序也很重要。

[PSEUDOCODE]

lst = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['c', 'b', 'a'] ]
print( count(lst) )


> { ['a', 'b', 'c'] : 2, ['d', 'e', 'f']: 1, ['c', 'b', 'a']: 1 }

一个重要因素是 ['a', 'b', 'c'] != ['c', 'b', 'a']

我试过:

from collections import counter
print( Counter([tuple(x) for x in lst]) )
print( [[x, list.count(x)] for x in set(lst)] )

两者都导致 ['a', 'b', 'c'] = ['c', 'b', 'a'],这是我不想要的一件事

我也试过:

from collections import counter
print( Counter( lst ) )

这只会导致错误;因为 lists 不能用作 dicts 中的 keys

有办法吗?

最佳答案

您不能将 list 作为 dict 的键,因为字典只允许不可变对象(immutable对象)作为键。因此,您需要首先将对象转换为元组。那么你可以使用 collection.Counter获取每个元组的计数:

>>> from collections import Counter
>>> my_list = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['c', 'b', 'a'] ]

#            v to type-cast each sub-list to tuple
>>> Counter(tuple(item) for item in my_list)
Counter({('a', 'b', 'c'): 2, ('d', 'e', 'f'): 1, ('c', 'b', 'a'): 1})

关于Python:计算列表中列表元素的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48053119/

相关文章:

Python:递归方法回滚变化?

mysql 在删除其中之一后更新表中的行

mysql - 统计mysql中文本字段中多个单词出现的次数

python - 在 Python 中使用正则表达式匹配输入

python - 从两个列表中获取对应的元素

java - 如何将对象添加到 Java 列表中?

c - 如何在 C 中创建函数(remove_by_index、remove_by_val)

javascript - 计算数组中出现的对 - Javascript

python - 如何在我的列表中找到具有相同元素的子列表的索引?

python - python中的嵌套字典在访问不存在的键时出错