【发布时间】:2019-09-21 22:17:02
【问题描述】:
我在Python中实现了一个生成器,问题是我想在生成器为空时返回“None”:
def permute(items):
permutations = [x for x in itertools.permutations(items)]
permutations.sort()
it = iter(permutations)
while True:
try:
new_items = yield next(it)
if new_items is not None:
permutations = [x for x in itertools.permutations(new_items)]
permutations.sort()
it = iter(permutations)
except StopIteration:
return None
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
我收到一个错误:
停止迭代
【问题讨论】:
-
我投票决定将此问题作为题外话结束,因为代码是从stackoverflow.com/a/55966743/8591431 复制的,然后在这里询问,而不是通过 cmets 跟进该答案!
-
@DeveshKumarSingh 我在提到的链接中没有看到相同的代码。编辑:我猜你编辑了你的链接
-
如果仔细观察,唯一的区别是
new_items = yield next(it, None)而不是new_items = yield next(it)! -
您是只想在生成器正常完成之前产生一次
None,还是希望它无限期地产生None,这样任何试图运行生成器的东西都会耗尽(例如@987654328 @) 会无限循环吗?