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

时间:2015-02-13 17:42:00

标签: python nested-loops

我有一个像这样的程序:

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个noughts或2个十字架和1个空字段然后它需要将该字段附加到列表中,在我的示例中,程序将永远不知道是否有人可以通过获取该空字段来获胜)

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

使用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