【问题标题】:how to use iterator in while loop statement in python如何在python的while循环语句中使用迭代器
【发布时间】:2020-03-24 07:54:29
【问题描述】:

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

有人知道怎么做吗?

【问题讨论】:

  • 必须是一个while循环吗? for x in i 将是自然的方式。
  • 我猜你不会在it = itertools.count(); while next(it):上尝试你的想法
  • 你能提供更多关于你的用例的上下文吗?
  • 您将如何访问 iter 返回的值,因为您不存储它,您只需获取项目并评估其布尔结果,那么您将在循环中做什么,因为您无权访问从返回的项目迭代器?
  • 如果我们想保持一般性怎么办,这就是为什么我没有指出具体的附加逻辑。这里的停止因素可以假设为超过最后一次迭代到迭代器抛出异常的地方。 @RomanPerekhrest

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


【解决方案1】:

你只需要安排你的迭代器在它过期时返回一个类似假的值。例如,如果我们反转 range 使其倒计时到 0:

>>> i = iter(range(5, -1, -1))
>>> while val := next(i):
...     print('doing something here with value', val)
...

这将导致:

doing something here with value 5
doing something here with value 4
doing something here with value 3
doing something here with value 2
doing something here with value 1

【讨论】:

  • 但这会消耗next(i),如果你在循环体中再次调用它,你会错过一个值。不过,也许使用 Python 3.8 赋值表达式。
  • 当然,这将是使用赋值表达式的完美场所。从问题中不清楚您是否关心迭代器的价值。
  • 更新了示例以使用赋值表达式。
【解决方案2】:

你可以的

    a = iter(range(10))

    try:
        a.next()
        while True and {True or False logic}:
            print("Bonjour")
            a.next()
    except StopIteration:
        print("a.next() Stop iteration")

【讨论】:

  • while True and (True or False):--这是在开玩笑吗?
  • @Chris_Rands 不,这是他[一些逻辑]的替代品
  • 这正是我不想做的。我想将下一个放在 while 语句中。
  • 知道了(不是我的 dv),你也应该在 py 3 中使用 next(a)
【解决方案3】:

while next(i):有两个问题

  1. for 循环不同,while 循环不会捕获在没有next 值时引发的StopIteration 异常;在这种情况下,您可以使用 next(i, None) 返回一个“假”值,但是只要迭代器返回一个实际的假值,while 循环也会停止
  2. next 返回的值将被消耗,循环体中不再可用。 (在 Python 3.8+ 中,这可以通过赋值表达式来解决,请参阅其他答案。)

相反,您可以使用带有itertools.takewhilefor 循环,从可迭代对象中测试当前元素,或者只是任何其他条件。这将循环直到迭代器用尽,或者条件评估为假。

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

【讨论】:

  • 一切都被否决了..这似乎是一个完全有效的问题/答案。
【解决方案4】:

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

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

在 Python 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

【讨论】:

  • None 参数很重要,否则会抛出stopIteration 异常
  • 如果集合或流中的元素是 None 怎么办?
【解决方案5】:
a = iter(range(10))

try:
    next(a)
    while True:
        print(next(a))
except StopIteration:
    print("Stop iteration")

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2021-03-19
  • 2017-02-17
  • 1970-01-01
  • 2020-04-10
  • 2013-01-01
  • 2015-09-14
  • 1970-01-01
  • 1970-01-01
  • 2021-03-07
相关资源
最近更新 更多