如何在python中的while循环语句中使用迭代器

新手上路,请多包涵

是否可以在 Python 的 while 循环中使用生成器或迭代器?例如,像这样的东西:

 i = iter(range(10))
while next(i):
    # your code

这样做的目的是在 while 循环语句中构建迭代,使其类似于 for 循环,不同之处在于您现在可以在 while 语句中添加额外的逻辑:

 i = iter(range(10))
while next(i) and {some other logic}:
    # your code

然后它变成了一个很好的 for 循环/while 循环混合体。

有谁知道如何做到这一点?

原文由 Union find 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 816
2 个回答

在 Python >= 3.8 中,您可以使用 赋值表达式 执行以下操作:

 i = iter(range(10))
while (x := next(i, None)) is not None and x < 5:
    print(x)

在 Python < 3.8 中,您可以使用 itertools.takewhile

 from itertools import takewhile

i = iter(range(10))
for x in takewhile({some logic}, i):
    # do stuff

这里的“一些逻辑”将是一个 1-arg 可调用函数,接收任何 next(i) 产生:

 for x in takewhile(lambda e: 5 > e, i):
    print(x)
0
1
2
3
4

原文由 user2390182 发布,翻译遵循 CC BY-SA 4.0 许可协议

while next(i):

  1. Unlike a for loop, the while loop will not catch the StopIteration exception that is raised if there is no next value;在这种情况下,您可以使用 next(i, None) 返回“假”值,但是 while 循环也会在迭代器返回实际假值时停止
  2. next 返回的值将被消耗并且在循环体中不再可用。 (在 Python 3.8+ 中,这可以通过赋值表达式解决,参见其他答案。)

相反,您可以将 for 循环与 itertools.takewhile 一起使用,测试可迭代的当前元素或任何其他条件。这将循环直到 iterable 耗尽,或者条件评估为 false。

 from itertools import takewhile
i = iter(range(10))
r = 0
for x in takewhile(lambda x: r < 10, i):
    print("using", x)
    r += x
print("result", r)

输出:

 using 0
...
using 4
result 10

原文由 tobias_k 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题