小编Kyl*_*ion的帖子

在 Python 中设置无限生成器的限制

我试图使下面的生成器能够设置返回数字的上限。

调用会list(it.takewhile(lambda x: x < 100, get_primes()))按预期返回 100 以下所有素数的列表,但list(get_primes(100))(应该以相同的方式返回相同的列表)仅返回一个空列表。

显然,我可以在循环if n and candidate>=n: break中包含一个for,但我最感兴趣的是为什么该if n: return构造不能像我期望的那样工作。它不应该只返回与takewhile上面相同的迭代器吗?我在这里忽略了什么?

import itertools as it

def get_primes(n=None):
    """
    Generates primes to a max of n.

    >>> list(get_primes(100))
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
    """
    if n:
        return it.takewhile(lambda x: x < n, get_primes())
    composites …
Run Code Online (Sandbox Code Playgroud)

python python-3.x

5
推荐指数
1
解决办法
3335
查看次数

标签 统计

python ×1

python-3.x ×1