繁体   English   中英

在Python3中设置函数错误:列表是不可散列的类型

[英]Set function error in Python3: list is unhashable type

在草稿文件中运行以下代码时,一切正常:

x = [1,1,1]
print(set(x))
> {1}

但是当我运行以下代码时

class MyClass(object):
   def __init__(self):
         self.mylist = []
   def train(self,vector):
         self.mylist.append(vector)
         self.mylist = list(set(self.mylist))

我收到错误, TypeError: unhashable type: 'list'

这是什么问题

当您发出

x = [1,1,1]
set(x)

您正在根据x的元素构建一个set ,这很好,因为x的元素是int类型的,因此是不可变的。 但是, mylist是列表的列表(因为vector对象是列表)。 这里的问题是mylist中的列表是可变的,因此不能进行哈希处理。 这就是python拒绝构建set

您可以通过将vector列表转换为tuple来解决此问题。 元组是不可变的,因此Python从tuple对象列表构建set没有问题。

演示:

>>> lst = [[1,2], [3,4]]
>>> set(lst)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> set(map(tuple, lst))
set([(1, 2), (3, 4)])

这是对的。 列表不可哈希,因为它是可变的。 请改用元组。

暂无
暂无

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

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