首页 > 解决方案 > 列表/集合转换出错,为什么?

问题描述

这段代码:

testset = list(set(child).union(pot_deck))

曾经工作,制作testset一个由两个列表childpot_deck. 我在代码中更改了一些看似无关的内容,现在它带有一个 TypeError: unhashable type: 'list'.

我试过了

testset = list(set(child).union(set(pot_deck)))

也是,但结果相同。

标签: python

解决方案


具有简单原始值的列表应该是可散列的,至少它们在 Python 3.8 中:

In [5]: child = [1]

In [6]: pot_deck = [2]

In [7]: testset = list(set(child).union(pot_deck))
   ...:

In [8]: testset
Out[8]: [1, 2]

但是,如果您有一个列表列表,您将获得:

In [9]: child = [[1]]

In [10]: testset = list(set(child).union(pot_deck))
    ...:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-52828817787d> in <module>
----> 1 testset = list(set(child).union(pot_deck))

TypeError: unhashable type: 'list'

所以我认为这就是发生的事情。child你可以把里面的内容打印出来post_deck找出来。


推荐阅读