gpt4 book ai didi

python - 类型错误 : Unhashable type

转载 作者:IT老高 更新时间:2023-10-28 22:07:57 28 4
gpt4 key购买 nike

我正在尝试获取元组列表:类似于 [ [(1,0),(2,0),(3,0)],[(1,1),(2 ,1),(3,1)....]]我用了这个说法

set([(a,b)for a in range(3)]for b in range(3))

但它给了我一个错误

TypeError: unhashable type: 'list'

我有 2 个问题要问 Python Guru:

a) 当我查看 Hashable 的 Python 定义时 -

"An object is hashable if it has a hash value which never changes during its lifetime (it needs a hash() method)"

当我对上面的表达式使用 dir 函数时

dir([(a,b)for a in range(3)]for b in range(3))

似乎说 __hash__ 在那里。那么,为什么我会收到错误消息?

我能够得到 [[(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1) ], [(0, 2), (1, 2), (2, 2)]]通过使用列表命令:

list(list((a,b) for a in range(3)) for bin range(3))

b)list 和 set 都将 Iterable 作为参数。为什么一个有效(列表)而另一个无效(设置)?

最佳答案

您正在通过 set(...) 调用创建一个 set,而 set 需要可散列的项目。你不能有一组列表。因为列表不是可散列的。

[[(a,b) for a in range(3)] for b in range(3)] 是一个列表。它不是可散列的类型。您在 dir(...) 中看到的 __hash__ 不是方法,它只是 None。

列表推导返回一个列表,您不需要在此处显式使用列表,只需使用:

>>> [[(a,b) for a in range(3)] for b in range(3)]
[[(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)]]

试试这些:

>>> a = {1, 2, 3}
>>> b= [1, 2, 3]
>>> type(a)
<class 'set'>
>>> type(b)
<class 'list'>
>>> {1, 2, []}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> print([].__hash__)
None
>>> [[],[],[]] #list of lists
[[], [], []]
>>> {[], [], []} #set of lists
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

关于python - 类型错误 : Unhashable type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6754102/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com