我正在尝试计算列表中元素出现的次数,如果这些元素也是列表的话。顺序也很重要。
[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/