如何有条件地跳过python中的for循环中的迭代步骤数? [英] How to conditionally skip number of iteration steps in a for loop in python?

查看:99
本文介绍了如何有条件地跳过python中的for循环中的迭代步骤数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个列表item_list

item_list = ["a", "b", "XYZ", "c", "d", "e", "f", "g"]

我们使用for循环遍历其项目,如果项目是"XYZ",则跳过项目"c", "d", "e",然后继续执行"f":

We iterate over its items with a for loop, if item is "XYZ", skip items "c", "d", "e" and continue with "f":

for item in item_list:
    if item == "XYZ":
       do_something()
       skip_3_items() ----> skip items "c", "d", "e"
    else:
        do_something_else()

实现这一目标的最Python方式是什么?

What could be the most pythonic way to achieve this?

推荐答案

list_iter = iter(item_list)

for item in list_iter:
    if item == "XYZ":
        do_something()
        for _ in range(3):   # skip next 3 items
            next(list_iter, None)

# etc.

基本上,而不是直接遍历列表,而是为其创建一个称为 iterator 的抽象并对其进行遍历.您可以通过调用next(...)告诉迭代器前进到下一个项目,我们将执行三次以跳过下三个项目.下次通过循环,它将在此之后的下一个项目处提取.

Basically, rather than iterating over the list directly, you create an abstraction for it called an iterator and iterate over that. You can tell the iterator to advance to the next item by calling next(...) which we do three times to skip the next three items. The next time through the loop, it picks up at the next item after that.

这篇关于如何有条件地跳过python中的for循环中的迭代步骤数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆