简体   繁体   English

找出哪个列表包含字典中的值

[英]find out which list contains a value in a dictionary

I have written a chess program and are currently working my way through coding check.我编写了一个国际象棋程序,目前正在通过编码检查。 How can I work out which piece (key in the dictionary) has kingpos in their list?我怎样才能确定哪一块(字典中的键)在他们的列表中有kingpos

The example below should give an answer of 'ksbishop' .下面的示例应该给出'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 

You can use a list comprehension:您可以使用列表推导:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM