正如标题所述,我想检查列表中的一个元素(不管是哪一个)是否与Python 3.7中嵌套列表中每个列表中的至少一个元素匹配
以下是一个例子:
possible_moves = [(3,4), (3,5), (3,6)]
sum_of_lists = [
[(5,5), (5,6), (5,7)],
[(2,3), (2,2), (2,1), (2,0)],
[(6,4), (5,4), (4,4), (3,4), (2,4)]
]
我确信它可以通过for循环和break
/continue
来完成,但是这个问题让我很为难。我自己能够获得以下代码:
# going through my first list
for position in possible_moves:
# going through all sub lists in the nested list
for sub_list in sum_of_lists:
# going through every element of the sub_list
for move in sub_list:
# now checking if my position element matches the move element of the sub_list
if position == move:
# at this point i want to go to the next sub_list
# code
# if the position element does not match the move element i want to go to the next move
# if the position element does not match with any of the move elements i want to return
# an empty list and stop all loops
elif position != move:
# code
# if any of my position elements matches at least one move element of all sub_lists i
# want to return a new list (e.g. matching_element = []) that contains the specific
# element and stop all loops
之后,我将使用一个函数检查返回的列表是否为空。如果为空,则返回False;如果不为空,则返回True
编辑:
好的,我会尽力解释我为什么要这么做
我正在使用Python3.7和pygame创建一个国际象棋游戏,作为我的第一个编程(和python)项目。此问题发生在尝试创建一个正在工作的is_checkmate函数时,该函数用于检查国王是否将死
所以,实际上我脑子里想的是,有几个条件必须满足:
首先,国王不能在任何友好棋子后面隐藏,也不能再受到控制
其次,检查国王的攻击者不可能被敌人的棋子摧毁
第三(这是我的问题所涉及的),如果几个敌方棋子检查国王,我将它们的路径作为指向国王的坐标(由sum_of_lists
中的sub_列表表示),我想检查一个国王友好棋子是否可以用他可能的一个移动(由possible_moves
表示)阻挡所有三条道路
但是说实话,我刚刚意识到这个条件是没有用的,因为我认为一个国王友好的棋子不可能同时阻挡几个敌人棋子同时检查国王的路径
我希望你明白我的意思,因为我不知道如何更好地解释它
函数^{} 和^{} 对于类似的检查非常有用
因此,要检查元组是否在所有子列表中,可以执行以下操作:
如果现在您想检查任何位置是否满足该要求,您可以执行以下操作:
这只是意味着在所有列表的交叉处有一个元组,所以
(当然,如果在
if set(...)...:
这样的布尔上下文中使用set(...)...
,则不需要bool
调用。)首先,尽量不要有三个嵌套for循环。尝试使用一些函数
前
首先检查元素
e
是否在列表中:然后将此逻辑用作lambda函数:
然后通过大列表中的每个列表映射此函数
然后检查
match_all_lst
中的每个布尔值是否为True
如果您自己匹配某个值,则不必处理提前中断(短路)。默认情况下,像
in
或all
这样的函数会执行此操作正如我也提到的,我认为你试图用错误的方式做一些事情。这种结构对你想要实现的目标来说真的很糟糕。你应该考虑某种秩序,也许是一棵树或者别的什么东西。请更详细地解释你想要什么
相关问题 更多 >
编程相关推荐