[英]Python Generator expression: how to add AND conditions from a loop?
[英]How to add a limit in the generator expression Python
我在 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 个元素)或行进行匹配。
在这种情况下,使用 any 而不是 all 实际上有效。 All 只是为所有行/列打印 1。
def check_won(grids, user, n):
cnt = 0
for grid in grids:
if any(cell == user for cell in grid):
cnt += 1
if cnt == 4:
return True
return False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.