Skip iterations in enumerated list object (python)

前端 未结 6 2137
清歌不尽
清歌不尽 2021-02-14 19:33

I have the code

for iline, line in enumerate(lines):
    ...
    if :
        

I would like, as you c

6条回答
  •  一向
    一向 (楼主)
    2021-02-14 19:48

    The standard idiom for doing this is to make an iterator and then use one of the consumer patterns (see here in the itertools docs.)

    For example:

    from itertools import islice
    
    lines = list("abcdefghij")
    
    lit = iter(enumerate(lines))
    for iline, line in lit:
        print(iline, line)
        if line == "c":
            # skip 3
            next(islice(lit, 3,3), None)
    

    produces

    0 a
    1 b
    2 c
    6 g
    7 h
    8 i
    9 j
    

提交回复
热议问题