简体   繁体   English

python结合“ while循环”和“ for循环”来遍历一些数据

[英]python combine 'while loop' with 'for loop' to iterate through some data

I am new to python and in general to programming. 我是python的新手,并且对编程还是一个新手。 I am trying to combine 'while loop' with 'for loop' to iterate through some list but i am getting infinite loops. 我正在尝试将“ while循环”与“ for循环”结合起来以遍历某些列表,但是我遇到了无限循环。 here is the code 这是代码

l=[0,2,3,4]
lo=0
for i in range(len(l)):
     while (True):
          lo+=1
     if lo+l[i]>40:
         break
     print(lo)

similarly with this code i got the same endless loop i want an output when the condition 'lo+ l[i] is greater than 40 stops looping and gives the final 'lo'output or result. 与此代码类似,当条件'lo + 1 [i]大于40时,我得到了相同的无限循环,我希望输出停止循环并给出最终的'lo'输出或结果。 I tried every method of indentation of the print line,but could not get what i wanted. 我尝试了每一种压痕打印线的方法,但无法获得我想要的。 please comment on this code. 请对此代码发表评论。 thanks in advance. 提前致谢。

You get infinite loop because you wrote the infinite loop. 您会遇到无限循环,因为您编写了无限循环。 You've probably thought that the break statement will somehow "magically" know that you don't want to end just the for loop, but also the while loop. 您可能已经想到, break语句将以某种方式“神奇地”知道您不希望仅结束for循环,也不想结束while循环。 But break will always break only one loop - the innermost one. 但是break只会打破一个循环-最里面的循环。 So that means that your code actually does this: 因此,这意味着您的代码实际上是这样做的:

while (True):               # <- infinite while loop
    lo += 1
    for i in range(len(l)): # <- for loop
        if not l[i] < 3:
            break           # <- break the for loop
        print(lo)
    # while loop continues

If you want to end both loops, you have to do it explicitly - for example, you can use a boolean variable: 如果要结束两个循环,则必须显式地执行它-例如,可以使用布尔变量:

keep_running = True
while (keep_running):
    lo += 1
    for i in range(len(l)):
        if not l[i] < 3:
            # this will effectively
            # stop the while loop:
            keep_running = False
            break
        print(lo)

Your break cancels the inner loop 你的休息取消了内循环

this will work: 这将工作:

l=[0,1,2,3,4] 
stop = False
lo=0 
while( not stop):
    lo+=1 
    for i in range(len(l)):
        if not l[i]<3:
           stop = True
           break
        print(lo)

Try with this: 试试这个:

l=[0,1,2,3,4]
lo=0

for i in l:
    lo+=1
    if not l[i]<3:
        break
    print(lo)

You don't need the external infinite loop and you don't have to manage the index yourself (see enumerate in the documentation). 您不需要外部无限循环,也不必自己管理索引(请参阅文档中的枚举 )。

l = [0,1,2,3,4]
for index, value in enumerate(l):
    if value >= 3:
         break
    print(index)

I changed the condition if value not < 3: to if value >= 3: for improved readability. 为了提高可读性,我将条件设置为if value not < 3: if value >= 3: :。

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

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