Python3:TypeError:不可哈希的类型:'list'在使用Counter时

10 投票
1 回答
23960 浏览
提问于 2025-04-17 23:25

我正在使用Python 3,下面是我的代码:

from collections import Counter
c = Counter([r[1] for r in results.items()])

但是当我运行它时,出现了这个错误:

Traceback (most recent call last):
  File "<pyshell#100>", line 1, in <module>
    c = Counter([r[1] for r in results.items()])
  File "C:\Python33\lib\collections\__init__.py", line 467, in __init__
    self.update(iterable, **kwds)
  File "C:\Python33\lib\collections\__init__.py", line 547, in update
    _count_elements(self, iterable)
TypeError: unhashable type: 'list'

我为什么会遇到这个错误呢?这段代码最开始是为Python 2写的,但我现在在Python 3中使用它。Python 2和Python 3之间有什么变化吗?

1 个回答

8

文档上说:

Counter 是一个字典的子类,用来计算可哈希对象的数量。

在你的情况中,results 看起来是一个字典,里面包含了 list 对象,而列表是不可哈希的。

如果你确定这段代码在 Python 2 中能正常工作,可以打印一下 results 来看看里面的内容。

Python 3.3.2+ (default, Oct  9 2013, 14:50:09) 
>>> from collections import Counter
>>> results = {1: [1], 2: [1, 2]}
>>> Counter([r[1] for r in results.items()])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/vic/projects/venv/trains/lib/python3.3/collections/__init__.py", line 467, in __init__
    self.update(iterable, **kwds)
  File "/home/vic/projects/venv/trains/lib/python3.3/collections/__init__.py", line 547, in update
    _count_elements(self, iterable)
TypeError: unhashable type: 'list'

顺便说一下,你可以简化你的构造方式:

Counter(results.values())

撰写回答