【问题标题】:In a for loop, if my iterator satisfies a condition, how can I pass to the next iterator?在 for 循环中,如果我的迭代器满足条件,我如何传递给下一个迭代器?
【发布时间】:2015-08-14 19:19:59
【问题描述】:

我需要一些关于for loop 的帮助。

如果我使用for 语句循环遍历项目列表,如果实际满足条件,我应该如何传递到下一个迭代器?

例子:

for item in list:
    if item == 10:
        next_item
    else:
        do_something

我应该写什么而不是next_item

【问题讨论】:

  • 使用continue 而不是next_item

标签: python for-loop iterator continue


【解决方案1】:

continue 可以。但是,为什么不呢:

for item in list:
    if item != 10:
        do_something

甚至:

[do_something(item) for item in list if item != 10]

【讨论】:

  • 如果他们想使用下一个值,那么这将不起作用
  • @PadraicCunningham,我 99% 确定 OP 只是在询问如何跳到下一个迭代并且不知道要使用什么术语。
【解决方案2】:

我想你的意思是获取 if 中的下一个元素,你可以使用 iter 调用 next 从 if 语句中的列表中获取下一个元素:

lst = [1,2,3,4]
it = iter(lst)
for item in it:
    if item == 10:
        nxt = next(it,None)
    else:
        do_something

在使用 nxt 做任何事情之前,您可能需要检查 if nxt is not None,如果您可能有 None 的使用对象:

lst = [1,2,3,4]
obj = object()
it = iter(lst)
for item in lst:
    if item == 10:
        nxt = next(it, obj)
        if nxt is not obj:
            # do whatever
    else:
        do_something

【讨论】:

  • 再一次,您的回答清除了我看待问题的方式,并为我增加了一些知识......呵呵,谢谢@PadraicCunningham!但就像 ndn 所说,我只是在寻找特定的术语。
猜你喜欢
  • 1970-01-01
  • 2020-06-16
  • 2021-05-15
  • 2014-11-11
  • 1970-01-01
  • 2017-10-05
  • 2015-04-15
  • 2021-08-14
  • 1970-01-01
相关资源
最近更新 更多