How to conditionally skip number of iteration steps in a for loop in python?

后端 未结 6 903

We have a list item_list,

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

We iterate over its items with a

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-25 01:15

    Use an iterator:

    $ 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
    

    This gives:

    $ python t.py 
    a
    b
    XYZ
    f
    g
    

提交回复
热议问题