简体   繁体   中英

A for loop inside a generator?

So recently we went over generators in the lecture, and this is my teacher's example:

from predicate import is_prime 
def primes(max = None):
    p = 2
    while max == None or p <= max:
        if is_prime(p):
            yield p
        p += 1

If we run

a = primes(10)
print(next(a) --> 2
print(next(a) --> 3
...

So this particular example of a generator uses a while loop and runs the function based on that, but can a generator also have a for loop? Like say

for i in range(2, max+1):
    # ...

Would these two operate similarly?

The only thing special about generators is the yield keyword and that they are paused between calls to the generator next() function.

You can use any loop construct you like, just like in 'normal' python functions.

Using for i in range(2, max + 1): would work the same as the while loop, provided that max is set to something other than None :

>>> def primes(max):
...     for p in range(2, max + 1):
...         if is_prime(p):
...             yield p
... 
>>> p = primes(7)
>>> next(p)
2
>>> next(p)
3
>>> next(p)
5
>>> next(p)
7
>>> next(p)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

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