嵌套列表中的嵌套循环

时间:2015-10-18 20:43:20

标签: python nested-loops nested-lists

我正在尝试在python中构建一个简单的Tic-Tac-Toe游戏,以检查胜利我使用嵌套循环来搜索嵌套列表中的匹配。出于某种原因,我的代码只搜索第一个嵌套列表,而不是我预期的其余部分。

board = [ 'O', 'X', ' ', 'O', ' ', 'X', 'O', 'X', 'X' ]
wins = [[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 checkWin(player):
    win = False
    for test in wins:
        print (test)
        count = 0
        for squares in test:
            if board[squares] == player:
                count = count + 1
            if count == 3:
                win = True
        return win

if __name__ == '__main__':
    print ("\nChecking board for X win ...\n")
    if checkWin("X"): 
        print ("Game over, X wins!")

    print ("\nChecking board for O win ...\n")
    if checkWin("O"):
        print ("Game over, O wins")

根据董事会提供的O预计胜利,这是我得到的输出:

Checking board for X win ...

[0, 1, 2]

Checking board for O win ...

[0, 1, 2]

有谁知道为什么会这样?

1 个答案:

答案 0 :(得分:1)

您从第一个嵌套列表测试返回,无论是否匹配这三个方块。相反,只有在DeviceWrapper为真时才返回:

Both

如果win为false,则上述内容将继续显示下一个测试的嵌套列表。

更好的是,只需在def checkWin(player): win = False for test in wins: count = 0 for squares in test: if board[squares] == player: count = count + 1 if count == 3: win = True if win: return True return False 设置为win时返回,因为您知道在该阶段找到了匹配项:

count

您可以使用all() function

,而不是计算
3
只要生成器表达式中的一个测试失败,

def checkWin(player): for test in wins: count = 0 for squares in test: if board[squares] == player: count = count + 1 if count == 3: return True return False 就会提前返回def checkWin(player): for test in wins: if all(board[square] == player for square in test): return True return False

最终版本添加any()以在一行中完成测试:

all()

演示:

False