繁体   English   中英

python 中的循环只需运行一次循环

[英]Loops in python need to run the loop only once

j=range(1,6)
for i in j:
     if(i==3):
         print("this is for i=3")
     else:
         print("this is for" + str(i))

我得到的 output 是

this is for1
this is for2
this is for i=3
this is for4
this is for5

我需要 output

this is for1
this is for i=3

我希望 else 循环应该只执行一次我尝试使用 break 也如果我使用 break if 循环没有执行

试试这个代码,它会给你你想要的结果:

j=range(1,6)
k=0
for i in j:
     if(i==3):
         print("this is for i=3")
     else:
         if (k==0):
             print("this is for" + str(i))
             k=1

如果你只想完成一次else ,你只需要记住这个事实,不要再做一次,比如:

j = range(1,6)
else_not_done = True
for i in j:
     if i == 3:
         print("this is for i=3")
     else:
         if else_not_done:
             print("this is for" + str(i))
             else_not_done = False

您可以使用elif或使用boolean object 只访问块内一次:

使用elif

j=range(1,6)
for i in j:
     if(i==3):
         print("this is for i=3")
     elif i == 1:
         print("this is for" + str(i))
     else:
        pass

使用 boolean object:

once = False    # to make sure we only visit once
for i in j:
    if(i==3):
        print("this is for i=3")
    else:
        if not once:
            print("this is for" + str(i))
            once = True   # set it to true to avoid visiting here again
    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM