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)])

这是正确的。列表不可散列,因为它是可变的。请改用元组。