python列表统计元素出现次数_Python:统计Lis中列表元素的出现次数

列表不可散列,但可以使用元组作为解决方法: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}

输出:

^{pr2}$

或者,如果您真的想使用列表,您可以创建一个自定义类来模拟字典哈希列表的功能: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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值