python - 计算重复列表的频率 - 在列表列表中

标签 python list python-2.7 counter

我在 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/

相关文章:

列表理解 : Even numbers from 0 to x

python - python 2.7中列表索引超出范围

python - Django 管理 css 丢失

python - 使用用户输入创建列表?销售计划,输入销售7天

python 3.4 列表理解 - 在列表中调用临时变量

Python 双向 TCP 套接字卡在 socket.recv 上

python - Scrapy 数据流以及项目和项目加载器

python - 如何使用 python 加载 *.hdr 文件

python - python导入excel文件并识别内容有删除线的单元格

python - 返回代码与退出状态