计算列表中的类似列表元素

时间:2014-04-03 07:40:52

标签: python list collections

我有一份清单

list = [[1,0],[1,2],[1,1],[1,0]]

现在我想计算上面列表中类似列表元素的出现次数。 例如; [1,0]:2, [1,2]:1, [1,1]:1

我做了

import collections
print Counter(list)

它抛出错误:

 Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/collections.py", line 352, in __init__
    self.update(iterable, **kwds)
  File "/usr/local/lib/python2.7/collections.py", line 434, in update
    self[elem] = self_get(elem, 0) + 1
TypeError: unhashable type: 'list'

我做错了什么?

2 个答案:

答案 0 :(得分:4)

Counter内部是字典。字典的键应该是乱码的。但是列表是可变的,并且它们不可清除。那就是你无法原样使用Counter

一种选择是将嵌套列表元素转换为元组

my_list = [[1,0],[1,2],[1,1],[1,0]]
from collections import Counter
print Counter(map(tuple, my_list))
# Counter({(1, 0): 2, (1, 2): 1, (1, 1): 1})

如果列表太大,那么您可以使用像这样的生成器表达式

print Counter(tuple(item) for item in my_list)

这将避免在内存中创建新列表,这与map不同。使用元组是有效的,因为元组是不可变的并且是可以清理的。

答案 1 :(得分:0)

如果我正确理解了您的问题,您应该可以像之前的问题一样使用.count()。 How can I count the occurrences of a list item in Python?

相关问题