Skip iterations in enumerated list object (python)

前端 未结 6 2164
清歌不尽
清歌不尽 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:58

    Use an external flag and set it when condition is met and check it in the beginning of cycle:

    ignore = 0
    for iline, line in enumerate(lines):
        if ignore > 0:
            ignore -= 1
            continue
    
        print(iline, line)
    
        if iline == 5:
            ignore = 5
    

    Or explicitly extract 5 elements from enumeration:

    enum_lines = enumerate(lines)
    for iline, line in enum_lines:
        print(iline, line)
    
        if iline == 5:
            for _, _ in zip(range(5), enum_lines):
                pass
    

    I personally prefer first approach, but second one looks more Pythonic.

提交回复
热议问题