Python3:TypeError:无法散列的类型:使用计数器时的“列表”

TJ1*_*TJ1 5 python counter typeerror python-3.3

我正在使用Python 3,并且有以下代码:

from collections import Counter
c = Counter([r[1] for r in results.items()])
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,我得到这个错误:

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'
Run Code Online (Sandbox Code Playgroud)

为什么会出现此错误?该代码最初是为Python 2编写的,但是我在Python 3中使用它。Python 2和3之间有什么变化吗?

war*_*iuc 7

文件说:

Counter 是用于计算可散列对象的 dict 子类。

在您的情况下,它看起来像是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'
Run Code Online (Sandbox Code Playgroud)

顺便说一下,您可以简化您的构造:

Counter(results.values())
Run Code Online (Sandbox Code Playgroud)