【发布时间】:2018-01-01 20:45:56
【问题描述】:
我正在尝试计算列表中元素的出现次数,如果这些元素也是列表的话。顺序也很重要。
[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。
有没有办法做到这一点?
【问题讨论】:
-
那么到目前为止你尝试过什么?
-
tuple(['a', 'b', 'c']) == tuple(['c', 'b', 'a'])给我False -
由于“列表不能用作字典中的键”,因此您想要的输出是不可能的;你想要什么?