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

How to make an if statement with multiple indices of a list equal to an object in the list?

在 python 中,我当前的代码工作到一定程度。我有另一个名为 check_X_win_status() 的函数,它与下面的函数做同样的事情,除了它检查 1,而不是 -1。任何人对如何使它更紧凑有任何想法?此外,我有时会收到一个错误,其中代码打印“win”,即使 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!")

首先,不是那样工作的,1 and -1 == -1 将 return true 当它是 false 时,你需要检查每个元素,即: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,这将消除输入触发多个 ifs 并开始多次打印的情况,如上所示

您可以通过准备一个表示为索引元组的获胜模式列表来稍微简化一下。然后,对于每个模式,使用 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.