简体   繁体   English

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

[英]Python3: TypeError: unhashable type: 'list' when using Counter

I am using Python 3 and I have this code: 我正在使用Python 3,并且有以下代码:

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

But when I run it I get this error: 但是当我运行它时,我得到这个错误:

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'

Why am I getting this error? 为什么会出现此错误? The code was originally written for Python 2, but I am using it in Python 3. Is there anything that changed between Python 2 and 3? 该代码最初是为Python 2编写的,但是我在Python 3中使用它。Python 2和3之间有什么变化吗?

The docs say: 文档说:

A Counter is a dict subclass for counting hashable objects. 计数器是用于计算可哈希对象的dict子类。

In your case it looks like results is a dict containing list objects, which are not hashable. 在您的情况下, results似乎是一个包含list对象的字典,该list对象不可哈希。

If you are sure that this code worked in Python 2, print results to see its content. 如果您确定此代码可在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'

By the way, you can simplify your construction: 顺便说一句,您可以简化您的构造:

Counter(results.values())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM