计算列表列表中列表的出现 [英] count occurrence of a list in a list of lists

查看:70
本文介绍了计算列表列表中列表的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python

我有一个清单清单.像

A = [[x,y],[a,b],[c,f],[e,f],[a,b],[x,y]]

我想计算每个列表在主列表中出现了多少次.

I want to count how many times each list occurred in the main list.

我的输出应该像

[x,y] = 2
[a,b] = 2
[c,f] = 1 
[e,f] = 1

推荐答案

只需使用collections中的Counter:

from collections import Counter
A = [[x,y],[a,b],[c,f],[e,f],[a,b],[x,y]]

new_A = map(tuple, A) #must convert to tuple because list is an unhashable type

final_count = Counter(new_A)


#final output:

for i in set(A):
   print i, "=", final_count(tuple(i))

这篇关于计算列表列表中列表的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆