【问题标题】:Python nesting elif,forPython 嵌套 elif,for
【发布时间】:2020-10-08 20:59:58
【问题描述】:

是否可以在 elif 中编写一个 for? 我有很多 elif 语句,我希望我的最后一个 elif 语句有一个 for inside elif 如何在 PYTHON 中编写嵌套 elif

def victory(see,z):
if see[0]==see[1]==see[2]==z:
        print(z,"wins")
    elif see[3]==see[4]==see[5]==z:
        print(z,"wins")
    elif see[6]==see[7]==see[8]==z:
        print(z,"wins")
    elif see[0]==see[3]==see[6]==z:
        print(z,"wins")
    elif see[1]==see[4]==see[7]==z:
        print(z,"wins")
    elif see[2]==see[5]==see[8]==z:
        print(z,"wins")
    elif see[0]==see[4]==see[8]==z:
        print(z,"wins")
    elif see[2]==see[4]==see[6]==z:
        print(z,"wins")
    elif for blank in see if blank=="_" or"__"or"___":
            print("game not finished")

【问题讨论】:

  • 为什么for 你到底在检查什么?
  • 请解释更多你试图做什么,这个不清楚,你只是想检查一个值是否在一个值列表中,或者对多个值执行一个操作
  • 可以在 elif 里面写一个 for 吗?
  • for inside elift or elfi with for?
  • for inside elif

标签: python function for-loop if-statement nested


【解决方案1】:

因为它是你的最后一个 elif,所以将其更改为 else 并在 else 块内创建一个 for 循环。然后,您可以在 for 循环中检查您的条件。

另外,您可以尝试类似代码的 switch 语句,而不是大量的 if elif else 语句

else: [print('game not finished') for blank in see if <condition>]

【讨论】:

    【解决方案2】:

    我认为你需要一个列表理解:

    elif [blank for blank in see if blank in ["_", “__", “___"] ]:
        print("some text")
    

    如果列表推导式最终没有任何内容,则认为它是“虚假的”并且不会采用 elif。

    【讨论】:

    • 在使用 elif 时,如果一个条件为真,它会被执行,但在我的情况下,每次运行我的代码时都会执行上述语句
    【解决方案3】:

    如果您要检查列表中的某些值,您可以使用in 而不是遍历整个列表:

    if see[0]==see[1]==see[2]==z:
        print(z,"wins")
    elif see[3]==see[4]==see[5]==z:
        print(z,"wins")
    # ... lots of other elifs here
    elif "_" in see or "__" in see or "___" in see:
        print("game not finished")
    

    【讨论】:

      猜你喜欢
      • 2016-08-30
      • 1970-01-01
      • 2012-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-18
      • 1970-01-01
      相关资源
      最近更新 更多