python - 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)
解决方案
在您的代码中是一个列表,它不能是字典键。请按照代码中的注释如何解决该问题:
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)
希望它有助于解决问题。
推荐阅读
- javascript - Why can't I use Jinja in Javascript for a django site?
- smartystreets - 如何从 SmartyStreet API 获取国家、州、县和城市?
- c++ - 将数组写入位图c ++
- c# - 无法在 MVC 客户端中使用 JWT 进行身份验证
- dart - Flutter 菜单和导航
- function - 带有 security() 的 Tradingview 自定义函数
- c++ - OpenGL:读取颜色缓冲区
- php - How to get last inserted non incremental id using eloquent in Laravel?
- angular - 在 Angular 中使用自定义 http 请求时,如何禁用 'sent' event.type?
- javascript - 登录验证 If Else 语句问题