首页 > 解决方案 > 带有列表的字典:TypeError:不可散列的类型:'list'

问题描述

我有这样一个方法:

def satisfied(self, assignment: Dict[str, List[str]]) -> bool:
        row: str = self.variables[0]
        column: str = self.variables[1]

        # If either variable is not in the assignment then it is not
        # yet possible for them to conflict
        if row not in assignment or column not in assignment:
            return True

        row_num: int = int(row[3:])
        col_num: int = int(column[3:])

        return assignment[row][col_num] == assignment[col][row_num] # here is this error

它被称为:

def revise_during_search(self, x: V, y: V, value: D, constraint: Constraint[V, D], purged_values: Dict[V, List[D]]) -> bool:
        revised: bool = False
        for val in self.domains[y]: # val is also type of D
            if not constraint.satisfied({x: value, y: val}):
            ... something happens here

所以你可以看到Vis strnad Dis List[str]

satisfied方法被调用时,我得到这样的错误:

File "file.py", line 87, in satisfied
    return assignment[row][col_num] == assignment[col][row_num]
TypeError: unhashable type: 'list'

但我不明白,因为当我调用时assignment[row],字符串 where rowis 它给了我 aList并且我使用col_numwhich 是一个数字来获取特定值。

标签: pythonpython-3.xlistdictionary

解决方案


很可能self.variables[0]orself.variables[1]是一个列表,你不能使用这一行:

if row not in assignment or column not in assignment:

在字典中搜索列表的前:

[123] in {1: 2}

输出:

TypeError: unhashable type: 'list'

另外,您可以检查col未在函数中定义的变量,这可能是list


推荐阅读