简体   繁体   中英

how to use iterator in while loop statement in python

Is it possible to use a generator or iterator in a while loop in Python? For example, something like:

i = iter(range(10))
while next(i):
    # your code

The point of this would be to build iteration into the while loop statement, making it similar to a for loop, with the difference being that you can now additional logic into the while statement:

i = iter(range(10))
while next(i) and {some other logic}:
    # your code

It then becomes a nice for loop/while loop hybrid.

Does anyone know how to do this?

In Python < 3.8 you can use itertools.takewhile :

from itertools import takewhile

i = iter(range(10))
for x in takewhile({some logic}, i):
    # do stuff

"Some logic" here would be a 1-arg callable receciving whatever next(i) yields:

for x in takewhile(lambda e: 5 > e, i):
    print(x)
0
1
2
3
4

In Python >= 3.8, you can do the following, using assignment expressions :

i = iter(range(10))
while (x := next(i, None)) is not None and x < 5:
    print(x)

There are two problems with while next(i):

  1. Unlike a for loop, the while loop will not catch the StopIteration exception that is raised if there is no next value; you could use next(i, None) to return a "falsey" value in that case, but then the while loop will also stop whenever the iterator returns an actual falsey value
  2. The value returned by next will be consumed and no longer available in the loop's body. (In Python 3.8+, that could be solved with an assignment expression, see other answer.)

Instead, you could use a for loop with itertools.takewhile , testing the current element from the iterable, or just any other condition. This will loop until either the iterable is exhausted, or the condition evaluates to false.

from itertools import takewhile
i = iter(range(10))
r = 0
for x in takewhile(lambda x: r < 10, i):
    print("using", x)
    r += x
print("result", r)

Output:

using 0
...
using 4
result 10

You just need to arrange for your iterator to return a false-like value when it expires. Eg, if we reverse the range so that it counts down to 0:

>>> i = iter(range(5, -1, -1))
>>> while val := next(i):
...     print('doing something here with value', val)
...

This will result in:

doing something here with value 5
doing something here with value 4
doing something here with value 3
doing something here with value 2
doing something here with value 1
a = iter(range(10))

try:
    next(a)
    while True:
        print(next(a))
except StopIteration:
    print("Stop iteration")

You can do

    a = iter(range(10))

    try:
        a.next()
        while True and {True or False logic}:
            print("Bonjour")
            a.next()
    except StopIteration:
        print("a.next() Stop iteration")

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