【问题标题】:A for loop inside a generator?生成器内的 for 循环?
【发布时间】:2015-04-01 21:36:46
【问题描述】:

所以最近我们在讲座中讨论了生成器,这是我老师的例子:

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

如果我们运行

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

所以这个特定的生成器示例使用while 循环并基于它运行函数,但是生成器也可以有for 循环吗?喜欢说

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

这两个操作会相似吗?

【问题讨论】:

  • 是的。为什么不呢?
  • @ColonelThirtyTwo 在讲座中,我的老师说过使用生成器的最常见方法之一是在 for 循环中,并且应该使用 while 循环,以免在更大的函数中混淆两者.
  • @Tyler:也许你误会了?这里的while循环是用来让生成器无限循环,而不是区分事物。
  • @Tyler:此外,在循环中使用生成器在生成器中使用循环是不同的。
  • 旁白:max 是一个非常方便的内置函数 (docs) 的名称,因此不是一个很好的参数名称。 upper_limit 或其他更好的主意。

标签: python python-3.x for-loop while-loop generator


【解决方案1】:

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

您可以使用任何您喜欢的循环构造,就像在“普通”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

【讨论】:

    猜你喜欢
    • 2020-02-03
    • 1970-01-01
    • 2017-10-05
    • 2020-05-19
    • 2014-07-20
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多