相关疑难解决方法(0)

将"yield from"语句转换为Python 2.7代码

我在Python 3.2中有一个代码,我想在Python 2.7中运行它.我确实转换了它(已经把missing_elements两个版本的代码都放了)但我不确定这是否是最有效的方法.基本上如果yield frommissing_element功能的上半部分和下半部分有两个如下所示的调用会发生什么?两个部分(上部和下部)中的条目是否在一个列表中相互附加,以便父级递归函数与yield from调用一起使用并将两个部分一起使用?

def missing_elements(L, start, end):  # Python 3.2
    if end - start <= 1: 
        if L[end] - L[start] > 1:
            yield from range(L[start] + 1, L[end])
        return

index = start + (end - start) // 2

# is the lower half consecutive?
consecutive_low =  L[index] == L[start] + (index - start)
if not consecutive_low:
    yield from missing_elements(L, start, index)

# is the upper part consecutive?
consecutive_high =  L[index] …
Run Code Online (Sandbox Code Playgroud)

python yield generator python-2.x yield-from

66
推荐指数
4
解决办法
3万
查看次数

Python函数返回生成器而不是列表

我想在Python中使用素数,因此使用函数来创建Sieve of Eratosthenes:

def primes(limit):
    a = [True] * limit
    a[0] = a[1] = False

    for (i, isprime) in enumerate(a):
        if isprime:
            yield i
            for n in range(i*i, limit, i):
                a[n] = False
    return list(a)
Run Code Online (Sandbox Code Playgroud)

在我看来,这个函数肯定应该返回一个列表但是当我这样做时print(primes(1000))我只得到<generator object primes at 0x0000000002C5C558>输出.当使用print(list(primes(1000)))一切按预期工作时(打印质数列表).

我错过了什么?

为什么函数返回生成器而不是列表?

python list generator python-3.x

0
推荐指数
1
解决办法
891
查看次数

标签 统计

generator ×2

python ×2

list ×1

python-2.x ×1

python-3.x ×1

yield ×1

yield-from ×1