首页 > 解决方案 > TypeError:不可散列的类型:python国际象棋程序中的“列表”

问题描述

我正在编写一个国际象棋程序并且正在编写检查代码。我需要来自对手移动字典(其中包含国王的位置)的密钥,用于查找放置它的棋子的坐标。现在这给了我错误:

opponentpieceposition=opponentposition.get(piece)
TypeError: unhashable type: 'list'. 

注意下面的例子应该打印 (1,6)

king=(5,1)
opponentmoves={'ksknight': [(8, 3), (5, 2), (6, 3)],
 'ksbishop': [(3, 6), (4, 7), (5, 8), (1, 4), (1, 6), (3, 4), (4, 3), (5, 1), (6, 1)],
 'king': [(6, 1), (5, 2), (4, 1)],
 'queen': [(4, 5), (2, 4), (1, 3), (2, 6), (1, 7), (4, 4)],
 'qsknight': [(3, 3), (1, 3)]}
opponentposition={'ksknight': (1, 3), 
 'ksbishop': (1, 6), 
 'king': (6, 1), 
 'queen': (4, 5), 
 'qsknight': (3, 3)}
if king in [z for v in opponentmoves.values() for z in v]:
    piece=[key for key in opponentmoves if king in opponentmoves[key]]
    opponentpieceposition=opponentposition.get(piece)
    print(opponentpieceposition)

标签: pythonpython-3.xlistdictionary

解决方案


在您的代码中是一个列表,它不能是字典键。请按照代码中的注释如何解决该问题:

if king in [z for v in opponentmoves.values() for z in v]:
    piece = [key for key in opponentmoves if king in opponentmoves[key]]
    print(piece)  # Let's show what is piece
    # result is ['ksbishop']
    # so we need 1st element of the list pice
    opponentpieceposition=opponentposition.get(piece[0])  # take the 1st element
    print(opponentpieceposition)

希望它有助于解决问题。


推荐阅读