【问题标题】:How to make an if statement with multiple indices of a list equal to an object in the list?如何使具有列表的多个索引的 if 语句等于列表中的对象?
【发布时间】:2022-01-20 19:21:13
【问题描述】:

在 python 中,我当前的代码可以工作到某个点。我有另一个名为check_X_win_status() 的函数,它的作用与下面的函数相同,只是它检查的是1,而不是-1。有人对如何使它更紧凑有任何想法吗?此外,即使 game_status = -1, 1,-1, 0, 0, 0, 0, 0, 0,我有时也会收到代码打印“win”的错误

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!")

【问题讨论】:

  • if game_status[0] and game_status[1] and game_status[2] == -1 这不是你想的那样。见this question

标签: python list indices


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    首先,这种方式不起作用,1 and -1 == -1 将返回 true,当它是 false 时,您需要检查每个元素,即:1 == -1 and -1 == -1

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

    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 并开始多次打印的情况,如上所示

    【讨论】:

    • 一致增量?我在考虑一个 for 循环,但它们似乎并没有以任何特定的模式递增
    猜你喜欢
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多