[英]How to get None when the iterator is empty in Python
I implemented a generator in Python, the problem is that I want to return "None" when the generator is empty:我在 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))
I get an error:我收到一个错误:
StopIteration停止迭代
Your problem is the next(iter, None)
.你的问题是next(iter, None)
。 You loop never ends.你循环永无止境。 It works correctly for 6 times, and then, you start yielding None
.它可以正常工作 6 次,然后,您开始产生None
。 That when you get the error.当你得到错误时。
Remove the None
, so that you cause a StopIteration
and cause the outer loop to end删除None
,以便您导致StopIteration
并导致外部循环结束
list(permute(['b', 'a', 'c']))
will return a list of the output of the generator.将返回生成器输出的列表。
However, your generator seem to return an infinite loop.但是,您的生成器似乎返回了一个无限循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.