类型错误:列表对象不可更改

2024-10-17 02:25:43 发布

您现在位置:Python中文网/ 问答频道 /正文

totalCost = problem.getCostOfActions(self.actions)

Tags: selfactionsproblemtotalcostgetcostofactions
3条回答

看起来你在试图用一个列表作为字典中的键或类似的东西。列表是不可哈希的,因此它们不能用作字典键或集合。

另一方面,python会在发生此类错误时提供stacktrace,其中包括文件名和行号。你应该可以用它来追踪违规代码。

编辑关于stacktraces:

cat > script.py
foo = [1,2,3]
bar = {}
bar[foo] = "Boom"
print "Never happens"

python script.py
Traceback (most recent call last):
  File "script.py", line 3, in <module> // this is the file and the line-number
   bar[foo] = "Boom"
TypeError: unhashable type: 'list'

您可能尝试过将列表等可变对象用作字典的键,或用作集合的成员。不能有效地和可预测地跟踪可变项,因此它们不提供哈希特殊属性。

将不可更改的类型添加到集合时会产生错误。

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

我想这也可能是你的情况。使用元组而不是列表:

>> a.add((3,4))
>>> 

相关问题 更多 >