[英]Python: Counting occurrences of List element within List
我正在尝试计算列表中元素出现的次数,如果这些元素也是列表。 顺序也很重要。
[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
。
有没有办法做到这一点?
列表不可散列,但您可以使用元组作为解决方法:
l = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['c', 'b', 'a'] ]
new_l = list(map(tuple, l))
final_l = {a:new_l.count(a) for a in new_l}
输出:
{('a', 'b', 'c'): 2, ('d', 'e', 'f'): 1, ('c', 'b', 'a'): 1}
或者,如果你真的想使用列表,你可以创建一个自定义类来模拟字典哈希列表的功能:
class List_Count:
def __init__(self, data):
new_data = list(map(tuple, data))
self.__data = {i:new_data.count(i) for i in new_data}
def __getitem__(self, val):
newval = [b for a, b in self.__data.items() if list(a) == val]
if not newval:
raise KeyError("{} not found".format(val))
return newval[0]
def __repr__(self):
return "{"+"{}".format(', '.join("{}:{}".format(list(a), b) for a, b in self.__data.items()))+"}"
l = List_Count([ ['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['c', 'b', 'a'] ])
print(l)
print(l[['a', 'b', 'c']])
输出:
{['a', 'b', 'c']:2, ['d', 'e', 'f']:1, ['c', 'b', 'a']:1}
2
您不能将list
作为dict
的键,因为字典只允许不可变对象作为键。 因此,您需要首先将对象转换为元组。 然后你可以使用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})
只需在某些等效类型上使用collections.Counter
但可散列: tuple
:
import collections
lst = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['c', 'b', 'a'] ]
c = collections.Counter(tuple(x) for x in lst)
print(c)
结果:
Counter({('a', 'b', 'c'): 2, ('d', 'e', 'f'): 1, ('c', 'b', 'a'): 1})
列表的另一种实现
l1 = [["a", "b", "c"], ["b", "c", "d"], ["a", "b", "c"], ["c", "b", "a"]]
def unique(l1):
l2 = []
for element in l1:
if element not in l2:
l2.append(element)
return l2
l2 = unique(l1)
for element in l2:
print(element, l1.count(element))
如果你想要一本字典,你可以把最后一部分改为
output = {element:l1.count(element) for element in unique(l1)}
不要使用列表作为变量名。
如果您不想使用任何模块,可以尝试这种方法:
list_1 = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['c', 'b', 'a'] ]
track={}
for i in list_1:
if tuple(i) not in track:
track[tuple(i)]=1
else:
track[tuple(i)]+=1
print(track)
输出:
{('a', 'b', 'c'): 2, ('d', 'e', 'f'): 1, ('c', 'b', 'a'): 1}
您还可以使用默认字典:
list_1 = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['c', 'b', 'a'] ]
track={}
import collections
d=collections.defaultdict(list)
for j,i in enumerate(list_1):
d[tuple(i)].append(j)
print(list(map(lambda x:{x:len(d[x])},d.keys())))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.