计算重复列表的频率-在列表列表中 [英] Count the frequency of a recurring list -- inside a list of lists

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

问题描述

我在python中有一个列表列表,我需要查找每个子列表出现了多少次.这是一个示例,

I have a list of lists in python and I need to find how many times each sub-list has occurred. Here is a sample,

from collections import Counter
list1 = [[ 1., 4., 2.5], [ 1., 2.66666667, 1.33333333], 
         [ 1., 2., 2.], [ 1., 2.66666667, 1.33333333], [ 1., 4., 2.5],
         [ 1., 2.66666667, 1.33333333]]   
c = Counter(x for x in iter(list1))
print c

如果列表中的元素是可哈希的(例如int),则上面的代码将起作用,但是在这种情况下,它们是列表,并且会出现错误

I above code will work, if the elements of the list were hashable (say int), but in this case they are lists and I get an error

TypeError: unhashable type: 'list'

我该如何计算这些列表,以便得到类似的信息

How can I count these lists so I get something like

[ 1., 2.66666667, 1.33333333], 3
[ 1., 4., 2.5], 2
[ 1., 2., 2.], 1

推荐答案

只需将列表转换为tuple:

>>> c = Counter(tuple(x) for x in iter(list1))
>>> c
Counter({(1.0, 2.66666667, 1.33333333): 3, (1.0, 4.0, 2.5): 2, (1.0, 2.0, 2.0): 1})

请记住对查找执行相同操作:

Remember to do the same for lookup:

>>> c[tuple(list1[0])]
2

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

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