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

后端 未结 6 909

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 would split the processing it two parts for sake of readability

    >>> 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()
    

提交回复
热议问题