如何在python中有条理地跳过for循环中的迭代步数?

时间:2014-01-16 17:58:39

标签: python list for-loop

我们有一个列表item_list

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

我们使用for循环迭代其项目,如果项目为"XYZ",则跳过项目"c", "d", "e"并继续"f"

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

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

6 个答案:

答案 0 :(得分:7)

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(...)告诉迭代器前进到下一个项目,我们会三次跳过接下来的三个项目。下一次循环时,它会在下一个项目之后接收。

答案 1 :(得分:2)

由于没有人提到过while循环,我会:

item_list = ["a", "b", "XYZ", "c", "d", "e", "f", "g"]
i = 0
while i < len(item_list):
    item = item_list[i]
    if item == "XYZ":
        do_something()
        i += 3
    else:
        do_something_else()
    i += 1

答案 2 :(得分:1)

使用迭代器:

$ cat t.py 
item_list = ["a", "b", "XYZ", "c", "d", "e", "f", "g"]

it = iter(item_list)
for item in it:
    if item == "XYZ":
       print item
       for _ in range(3):
           next(it, None)
    else:
        print item

这给出了:

$ python t.py 
a
b
XYZ
f
g

答案 3 :(得分:1)

为了便于阅读,我会将处理分为两部分

>>> def foo(item_list,key = "XYZ", skip = 3):
    from itertools import takewhile, islice
    def do_something():
        return "do_something()"
    def do_something_else():
        return "do_something_else()"
    it = iter(item_list)
    for items in takewhile(lambda e: e != key, it):
        print items, do_something_else()
    print do_something()
    it = islice(it,skip, None)
    for items in it:
        print items, do_something_else()


>>> foo(item_list)
a do_something_else()
b do_something_else()
do_something()
f do_something_else()
g do_something_else()

答案 4 :(得分:0)

我会存储一个处理跳过物品的计数器。

def skipper(item_list):
    skip_count = 0
    for item in item_list:
        if item == "XYZ":
            skip_count = 3
        else:
            if skip_count:
                skip_count -= 1
            else:
                # do_something()
                print item,

示例:

In [23]: item_list
Out[23]: ['a', 'b', 'XYZ', 'c', 'd', 'e', 'f', 'g']

In [24]: skipper(item_list)
a b f g

答案 5 :(得分:0)

我个人可能会这样写出来:

xyz_i = item_list.index('XYZ')

do_something('XYZ') #or do_something(item_list[xyz_i]) but.. just save yourself the list lookup

for x in item_list[xyz_i+4:]:
    do_something_else(x)