[英]Python3: TypeError: unhashable type: 'list' when using Counter
我正在使用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之间有什么变化吗?
文档说:
计数器是用于计算可哈希对象的dict子类。
在您的情况下, results
似乎是一个包含list
对象的字典,该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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.