我已经写了一个国际象棋程序,目前正在通过编码检查工作。如何确定清单中哪一个(词典中的键)中有kingpos

下面的示例应给出'ksbishop'的答案。

kingpos=(5,1)
movesdict={'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)]}
if kingpos in [z for v in movesdict.values() for z in v]:
# find out which key has it

最佳答案

您可以使用列表理解:

>>> [key for key in movesdict if kingpos in movesdict[key]]
['ksbishop']

09-27 00:05