【问题标题】:How to get None when the iterator is empty in Python当迭代器在Python中为空时如何获取None
【发布时间】: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 @) 会无限循环吗?

标签: python iterator


【解决方案1】:

您的问题是next(iter, None)。你循环永远不会结束。它可以正常工作 6 次,然后,您开始生成 None。当你得到错误时。

删除None,这样你就会导致StopIteration,并导致外循环结束

【讨论】:

  • 我试图移动 None 但我得到“RuntimeError: generator raise StopIteration”。
  • 实际上如何在生成器为空的情况下使用 next 方法返回“None”?
【解决方案2】:
list(permute(['b', 'a', 'c']))

将返回生成器的输出列表。

但是,您的生成器似乎返回了一个无限循环。

【讨论】:

  • 如果我移动None,当生成器为空时如何使用next方法返回“None”?
猜你喜欢
  • 2022-11-20
  • 1970-01-01
  • 2021-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-20
  • 2012-06-21
  • 2020-01-15
相关资源
最近更新 更多