我在Python中有一个函数,如果网格矩阵中的所有行或列都是相同的值,则返回true。但是,无论网格大小如何,我都希望函数一旦其中4个匹配就停止迭代并返回True。如何修改下面的生成器表达式以实现相同的效果?
def check_won(grids, user, n):
return any(all(cell == user for cell in grid) for grid in grids)
为了进一步说明,我分享了示例输出:
Input the grid size: 5
Current board:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
Input a slot player 1 from 1 to 5: 1
Current board:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
Input a slot player 2 from 1 to 5: 2
Current board:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[1, 2, 0, 0, 0]
Input a slot player 1 from 1 to 5: 1
Current board:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 2, 0, 0, 0]
Input a slot player 2 from 1 to 5: 2
Current board:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
Input a slot player 1 from 1 to 5: 1
Current board:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
Input a slot player 2 from 1 to 5: 2
Current board:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
Input a slot player 1 from 1 to 5: 1
Current board:
[0, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
Input a slot player 2 from 1 to 5: 2
Current board:
[0, 0, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
Input a slot player 1 from 1 to 5: 1
Current board:
[1, 0, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
Player 1 has won
可以看出,这不会以4个匹配项(匹配项4)退出,而是需要整列(此处显示5个元素)或行匹配。
def check_won(grids, user, n):
cnt = 0
for grid in grids:
if all(cell == user for cell in grid):
cnt += 1
if cnt == 4:
return True
return False