Python生成器仅返回yield的第一个实例

时间:2019-07-23 14:17:48

标签: python-3.x list generator yield

此代码应在调用“ next”时按顺序生成所有素数,但仅生成列表的第一个素数2。该列表可以正常生成素数。

def genPrime():
    x = 1
    primeList = [2]
    while True:
        x += 1
        tempList = []
        for i in range(len(primeList)):
            tempList.append(x % primeList[i])
        if min(tempList) > 0:
            next = primeList[-1]
            yield next
            primeList.append(x)

prime = genPrime()
print(prime.__next__())

1 个答案:

答案 0 :(得分:1)

这正是发电机应该做的。 .__next__()仅返回下一项,就如名称所示。

尝试:

print(prime.__next__())
print(prime.__next__())
print(prime.__next__())

您会看到他们一一得到。

此外,不要直接调用.__next__(),这一点很重要。正确的方法是:

print(next(prime))
print(next(prime))
print(next(prime))

如果全部想要,请执行以下操作:

for p in prime:
    print(p)

此外,尽管不是答案的一部分,但我给您提供了一些编程技巧:

for i in range(len(primeList)):
    tempList.append(x % primeList[i])

具有不必要的间接。随便

for prime in primeList:
    tempList.append(x % prime)

此外,不需要整个tempList。 只需使用for-else构造:

def genPrime():
    x = 1
    primeList = []
    while True:
        x += 1
        for prime in primeList:
            if x % prime == 0:
                break
        else:
            yield x
            primeList.append(x)