检查列表的元素是否在嵌套列表的每个列表中

2024-06-16 14:42:14 发布

您现在位置:Python中文网/ 问答频道 /正文

正如标题所述,我想检查列表中的一个元素(不管是哪一个)是否与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表示)阻挡所有三条道路

但是说实话,我刚刚意识到这个条件是没有用的,因为我认为一个国王友好的棋子不可能同时阻挡几个敌人棋子同时检查国王的路径

我希望你明白我的意思,因为我不知道如何更好地解释它


Tags: ofthetoin列表formoveif
3条回答

函数^{}^{}对于类似的检查非常有用

因此,要检查元组是否在所有子列表中,可以执行以下操作:

position = (3, 4)
print(all(position in sub_list for sub_list in sum_of_lists))

如果现在您想检查任何位置是否满足该要求,您可以执行以下操作:

print(any(all(position in sub_list for sub_list in sum_of_lists) for position in possible_moves))

I want to know if there is a tuple in possible_moves that also occurs in every sub_list of sum_of_lists.

这只是意味着在所有列表的交叉处有一个元组,所以

bool(set(possible_moves).intersection(*sum_of_lists))

(当然,如果在if set(...)...:这样的布尔上下文中使用set(...)...,则不需要bool调用。)

首先,尽量不要有三个嵌套for循环。尝试使用一些函数

nested = [[1, (5,3), 3], [1, 2, 3, (5,3)]]
move = (5, 3)

首先检查元素e是否在列表中:

e in lst

然后将此逻辑用作lambda函数:

lambda lst: move in lst

然后通过大列表中的每个列表映射此函数

match_all_lst = map(lambda lst: move in lst, nested)

然后检查match_all_lst中的每个布尔值是否为True

matches_all = all(match_all_lst)

如果您自己匹配某个值,则不必处理提前中断(短路)。默认情况下,像inall这样的函数会执行此操作

正如我也提到的,我认为你试图用错误的方式做一些事情。这种结构对你想要实现的目标来说真的很糟糕。你应该考虑某种秩序,也许是一棵树或者别的什么东西。请更详细地解释你想要什么

相关问题 更多 >