Python:如何在嵌套循环中检查条件



我有一个类似的程序:

one_tuple = ((0, 1, 2),
             (3, 4, 5),
             (6, 7, 8),
             (0, 3, 6),
             (1, 4, 7),
             (2, 5, 8),
             (0, 4, 8),
             (2, 4, 6))
def function():
    for tuples in one_tuple:
        for variables in tuple:
           see if ceratin conditions are true....

这是一个名为"Tic-tac-toe"的程序的人工智能,该部分检查每一个获胜组合,嵌套for循环似乎是最简单的解决方案(这就是为什么子元组有3个元素),我需要遍历每个元素并检查它们(例如,如果子元组有2个零或2个叉和1个空字段,那么它需要将该字段附加到列表中,在我的示例中,程序永远不会知道是否有人可以通过获取该空字段来获胜)

您可以对每个子元组使用all来检查该元组中每个元素的条件。例如,假设您想检查元组的所有元素是否都大于2

def foo(tup):
    for sub in tup:
        if all(i > 2 for i in sub):
            print("all greater than two")
>>> foo(one_tuple)
all greater than two
all greater than two

对棋盘和商店获胜组合使用dict。如果三个位置中有两个被填补,我们就知道剩下的位置是一个获胜的位置。这是one_tuple被获胜梳取代的逻辑的一个快速例子:

from collections import OrderedDict
# 8 potential winning combs for 9 item board
winning_combs = [(0, 1, 2), (0, 3, 6), (0, 4, 8), (3, 4, 5), (6, 7, 8), (1, 4, 7), (2, 5, 8), (2, 4, 6)]
# set all to False for an empty board
board = OrderedDict((k, False) for k in range(10))
board[0] = True # simulate two moves 0 and 1 are set 
board[1] =  True
# anywhere we find two positions taken in a potential winning combo we will return the key/position
opps = [k for tup in winning_combs if sum(board[t] for t in tup) == 2 for k in tup if not board[k]]
print(opps) # returns 2 the potential winning position

最新更新