Skip iterations in enumerated list object (python)

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

    Using the enumeration index

    Similar to the accepted answer… except without using itertools (IMHO islice doesn't improve readability), plus enumerate() already returns an iterator so you don't need the iter() at all:

    lines = [{str(x): x} for x in range(20)]  # dummy data
    
    it = enumerate(lines)
    for i, line in it:
        print(line)
    
        if i == 10:  # condition using enumeration index
            [next(it, None) for _ in range(5)]  # skip 5
    

    That last line can optionally be expanded for readability:

            for _ in range(5):  # skip 5
                next(it, None)
    

    The None argument in next() avoids an exception if there aren't enough items to skip. (For the original question, it can be omitted as the OP wrote: "I can be sure that, if the condition is met, there are 5 or more objects left in the lines object.")

    Not using the enumeration index

    If the skip condition isn't based on the enumeration index, simply treat the list as a FIFO queue and consume from it using pop():

    lines = [{str(x): x} for x in range(20)]  # dummy data
    
    while lines:
        line = lines.pop(0)  # get first item
        print(line)
    
        if :  # some other kind of condition
            [lines.pop(0) for _ in range(5)]  # skip 5
    

    As before, that last line can optionally be expanded for readability:

            for _ in range(5):  # skip 5
                lines.pop(0)
    

    (For large lists, use collections.deque for performance.)

提交回复
热议问题