在Python中,是否可以在while循环中使用生成器或迭代器?例如,像这样:
i = iter(range(10))
while next(i):
# your code
这样做的目的是将迭代构建到while循环语句中,使其类似于for循环,不同之处在于现在可以将其他逻辑加入while语句中。
这样做的目的是为了让while循环语句具有迭代功能,从而使其类似于for循环。与for循环的区别在于,您现在可以在while语句中添加其他逻辑:
i = iter(range(10))
while next(i) and {some other logic}:
# your code
然后它变成了一个很好的for循环/while循环混合体。
有人知道如何实现这个吗?
for x in i
是更自然的方式。 - user2390182it = itertools.count(); while next(it):
上尝试你的想法。 - RomanPerekhrestwhile
循环的停止因素应该是什么。那么it = iter([True, False, 1, 0, 1]); while next(it): print('1')
呢?给出的答案很简单,但你的确切意图是什么? - RomanPerekhrest