简体   繁体   中英

Python While Loop Condition Evaluation

Say I have the following loop:

i = 0
l = [0, 1, 2, 3]
while i < len(l):
    if something_happens:
         l.append(something)
    i += 1

Will the len(i) condition being evaluated in the while loop be updated when something is appended to l ?

是的,它会的。

Your code will work, but using a loop counter is often not considered very "pythonic". Using for works just as well and eliminates the counter:

>>> foo = [0, 1, 2]
>>> for bar in foo:
    if bar % 2: # append to foo for every odd number
        foo.append(len(foo))
    print bar

0
1
2
3
4

If you need to know how "far" into the list you are, you can use enumerate :

>>> foo = ["wibble", "wobble", "wubble"]
>>> for i, bar in enumerate(foo):
    if i % 2: # append to foo for every odd number
        foo.append("appended")
    print bar

wibble
wobble
wubble
appended
appended

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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