我在 python 中有一个列表列表,我需要找出每个子列表出现了多少次。这是一个示例,
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),我上面的代码将起作用,但在这种情况下它们是列表,我得到一个错误
TypeError: unhashable type: 'list'
我怎样才能计算这些列表,以便得到类似的东西
[ 1., 2.66666667, 1.33333333], 3
[ 1., 4., 2.5], 2
[ 1., 2., 2.], 1
最佳答案
只需将列表转换为元组
:
>>> 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})
记住对查找做同样的事情:
>>> c[tuple(list1[0])]
2
关于python - 计算重复列表的频率 - 在列表列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35316186/