计算重复列表的频率-在列表列表中
问题描述:
我在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