首页 > 解决方案 > 不可散列的类型列表

问题描述

我们有一S组元组。

每个元组是(string, string, list)

下面的代码:

def f(entry_set, def_dict, S):
    for entry in entry_set:
        if entry[1] in def_dict:
            S.add((entry[0], entry[1], def_dict[entry[1]]),) // error

给出错误:TypeError: unhashable type: 'list'

def_dict是用附加列表的值构造的。


对于添加条目,是否使用散列来查找集合元素的唯一性?

标签: pythonpython-3.xcollections

解决方案


Alist是一个可变引用,因此不能散列,因为它引用了内存。如果您可以将列表转换为元组,则可以散列它们。

set((1, 2, [3, 4]))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-d0176c73c39f> in <module>()
----> 1 set((1, 2, [3, 4]))

TypeError: unhashable type: 'list'

相对于:

set((1, 2, (3, 4)))
{(3, 4), 1, 2}

推荐阅读