【问题标题】:Python3: TypeError: unhashable type: 'list' when using CounterPython3:TypeError:不可散列的类型:使用计数器时的“列表”
【发布时间】:2014-04-30 00:31:14
【问题描述】:

我正在使用 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 和 3 之间有什么变化吗?

【问题讨论】:

    标签: python counter typeerror python-3.3


    【解决方案1】:

    docs 说:

    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'
    

    顺便说一句,你可以简化你的构造:

    Counter(results.values())
    

    【讨论】:

    • 你说得对,我的代码有误。现在结果是 dict class 我没有收到错误,感谢您的帮助。
    猜你喜欢
    • 2018-12-26
    • 2020-03-28
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 2012-10-27
    • 2019-01-29
    • 2012-02-19
    相关资源
    最近更新 更多