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

后端 未结 6 963

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:22

    I'd store a counter that handles skipping items.

    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,
    

    Example:

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

提交回复
热议问题