gpt4 book ai didi

python - 嵌套列表中的嵌套循环

转载 作者:太空宇宙 更新时间:2023-11-03 17:20:37 31 4
gpt4 key购买 nike

我正在尝试用 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]

有人知道为什么会发生这种情况吗?

最佳答案

无论这三个方 block 是否匹配,您都会从第一个嵌套列表测试中返回。相反,仅当 win 为 true 时才返回:

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 为 false,则上面的内容将继续到下一个嵌套列表以进行下一个测试。

更好的是,当 count 设置为 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

您可以使用all() function来代替计数。 :

def checkWin(player):
for test in wins:
if all(board[square] == player for square in test):
return True
return False

all() 一旦生成器表达式中的某个测试失败,就会提前返回 False

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

def checkWin(player):
return any(all(board[square] == player for square in test)
for test in wins)

演示:

>>> 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):
... return any(all(board[square] == player for square in test)
... for test in wins)
...
>>> checkWin('X')
False
>>> checkWin('O')
True

关于python - 嵌套列表中的嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33203038/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com