发电机内部的for循环?

2024-05-13 21:02:08 发布

您现在位置:Python中文网/ 问答频道 /正文

所以最近我们在讲座中回顾了发电机,这是我老师的例子:

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

如果我们逃跑

^{pr2}$

所以这个特定的生成器示例使用while循环并基于该循环运行函数,但是生成器是否也可以有一个for循环?比如说

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

这两者的运作方式会相似吗?在


Tags: fromimportnoneforisdef老师prime
1条回答
网友
1楼 · 发布于 2024-05-13 21:02:08

生成器唯一的特殊之处是yield关键字,并且它们在调用generatornext()函数之间被暂停。在

你可以使用任何你喜欢的循环结构,就像在普通的python函数中一样。在

使用for i in range(2, max + 1):将与while循环相同,前提是max被设置为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

相关问题 更多 >