首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python嵌套elif,for

Python嵌套elif,for
EN

Stack Overflow用户
提问于 2020-06-19 01:41:39
回答 3查看 309关注 0票数 1

有没有可能在elif内部写一个for?我有很多elif语句,我希望我的最后一个elif语句在elif内部有一个for,如何用PYTHON编写嵌套的elif

代码语言:javascript
运行
复制
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")
EN

回答 3

Stack Overflow用户

发布于 2020-06-19 01:49:34

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

此外,您可以尝试使用switch语句,如代码,而不是大量的if elif else语句

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

票数 0
EN

Stack Overflow用户

发布于 2020-06-19 01:51:09

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

代码语言:javascript
运行
复制
elif [blank for blank in see if blank in ["_", “__", “___"] ]:
    print("some text")

如果列表理解最终什么都没有,它就被认为是“错误的”,elif将不会被接受。

票数 0
EN

Stack Overflow用户

发布于 2020-06-19 02:06:16

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

代码语言:javascript
运行
复制
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")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62456155

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档