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

标签 python python-3.x while-loop iterator generator

是否可以在 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 循环混合体。

有人知道怎么做吗?

最佳答案

在 Python >= 3.8 中,您可以使用 assignment expressions 执行以下操作:

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

关于python - 如何在python中的while循环语句中使用迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59092561/

相关文章:

python - 显式欧拉方法的行为不符合我的预期

python - 无法保存和恢复经过训练的 TensorFlow 模型

Python/Kivy : conditional design in . kv 文件

python - 如何在 Python 中使用 .split 将未知数量的数字输入分配给变量?

python-3.x - 模块 'dask' 没有属性 'read_fwf'

c++ - 查找文件末尾的问题?

python - 具有已发布的 GIL 和复杂线程的多线程代码在 Python 中速度较慢

Python for 循环操作列表并删除曾经使用过的元素

c - While 循环检索输入,在 C 中无法正常工作

c++ - 我尝试用 C++ 编写自己的简单移动平均线