如何使列表的多个索引等于列表中的一个对象的if语句



在python中,我当前的代码在一定程度上起作用。我有另一个名为check_X_win_status()的函数,它做的事情与下面的函数相同,只是它检查1,而不是-1。有人对如何使其更紧凑有什么想法吗?此外,我有时会遇到一个错误,代码会打印";获胜";即使game_status=-1,1,-1,0,0,0,0,0,0

game_status = [-1,-1,-1,0,0,0,0,0,0]
def check_O_win_status():
if game_status[0] and game_status[1] and game_status[2] == -1:
print("O wins!")
if game_status[3] and game_status[4] and game_status[5] == -1:
print("O wins!")
if game_status[6] and game_status[7] and game_status[8] == -1:
print("O wins!")
if game_status[0] and game_status[3] and game_status[6] == -1:
print("O wins!")
if game_status[1] and game_status[4] and game_status[7] == -1:
print("O wins!")
if game_status[2] and game_status[5] and game_status[8] == -1:
print("O wins!")
if game_status[0] and game_status[4] and game_status[8] == -1:
print("O wins!")
if game_status[2] and game_status[4] and game_status[6] == -1:
print("O wins!")

您可以通过准备一个用索引元组表示的获胜模式列表来简化这一点。然后,对于每个模式,使用all((检查所有3个索引在game_status:中是否都有-1

def check_O_win_status():
winPatterns = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(0,4,8),(2,4,6)]
if any(all(game_status[i]==-1 for i in patrn) for patrn in winPatterns):
print("O wins")

在Python中,A and B and C == -1不会测试所有3个变量是否都等于-1。它将使用前两个变量作为布尔值,提取它们的Truthy值,就像执行(A == True) and (B == True) and (C==-1)一样。

为了测试所有3个变量都是-1,可以这样表示条件:A == B == C == -1

首先,如果不是这样,1 and -1 == -1将在false时返回true,您需要检查每个元素,即:1 == -1 and -1 == -1

其次,为什么要使用两个函数——你可以通过函数传递一个参数,然后进行比较。ei:

def check_win_status(num):
if game_status[0] == num and game_status[1] == num and game_status[2] == num:
elif game_status[3] == num and game_status[4] == num and game_status[5] == num:
#rest of your code here

另外,使用elif来检查下一个元素,而不是if,这将消除输入触发多个if并开始多次打印的情况,如上面所示

最新更新