gpt4 book ai didi

python - 类型错误 : unhashable type: 'list' when find the composition of a product

转载 作者:太空宇宙 更新时间:2023-11-04 09:32:32 24 4
gpt4 key购买 nike

我看了这么一道题

Person A is charged with the task of determining the ages of person B’s three children. B tells A that the product of the children’s ages is 36. After ­considering this clue, A replies that another clue is required, so B tells A the sum of the children’s ages. Again, A replies that another clue is needed, so B tells A that the oldest child plays the piano. After hearing this clue, A tells B the ages of the three children. How old are the three children?

开始分析乘积为 36 并尝试过的三元组

In [4]: ll = []
...: for x in range(1,37):
...: for y in range(1, 37):
...: for z in range(1, 37):
...: if x * y * z == 36:
...: l = sorted([x, y,z])
...: ll.append(l)
...: s = set(ll)
...: print(s)
...:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-cc3ad95c0d1b> in <module>()
6 l = sorted([x, y,z])
7 ll.append(l)
----> 8 s = set(ll)
9 print(s)
10

TypeError: unhashable type: 'list'

我对无法散列的类型列表感到很困惑。

最佳答案

set 对象是用哈希表实现的。这意味着您存储在其中的所有值都必须是可哈希的(也就是说,hash(value) 必须有效)。

您正在尝试从一个包含其他列表的列表构建一个集合。不幸的是,列表不可散列,因此您会收到标题中描述的错误。

有几种方法可以解决此问题。最简单的方法是使用 tuple 而不是内部列表。元组是可哈希的,只要它们的所有内容也是可哈希的(整数也是可哈希的,因此它们应该适合您)。

尝试将 ll.append(l) 更改为 ll.append(tuple(l)),您的代码应该可以正常工作。

关于python - 类型错误 : unhashable type: 'list' when find the composition of a product,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55132895/

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