【问题标题】:Python generator only returning first instance of yieldPython生成器只返回yield的第一个实例
【发布时间】:2019-12-01 14:54:54
【问题描述】:
当调用 '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__())
【问题讨论】:
标签:
python-3.x
list
generator
yield
【解决方案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)