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

后端 未结 6 907

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 00:58

    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.
    

    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.

提交回复
热议问题