Skip first entry in for loop in python?

前端 未结 13 2423
面向向阳花
面向向阳花 2020-12-02 05:15

In python, How do I do something like:

for car in cars:
   # Skip first and last, do work for rest
相关标签:
13条回答
  • 2020-12-02 06:16

    The other answers only work for a sequence.

    For any iterable, to skip the first item:

    itercars = iter(cars)
    next(itercars)
    for car in itercars:
        # do work
    

    If you want to skip the last, you could do:

    itercars = iter(cars)
    # add 'next(itercars)' here if you also want to skip the first
    prev = next(itercars)
    for car in itercars:
        # do work on 'prev' not 'car'
        # at end of loop:
        prev = car
    # now you can do whatever you want to do to the last one on 'prev'
    
    0 讨论(0)
提交回复
热议问题