是否可以在 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/