Skip first entry in for loop in python?

前端 未结 13 2488
面向向阳花
面向向阳花 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 05:50

    The best way to skip the first item(s) is:

    from itertools import islice
    for car in islice(cars, 1, None):
        # do something
    

    islice in this case is invoked with a start-point of 1, and an end point of None, signifying the end of the iterator.

    To be able to skip items from the end of an iterable, you need to know its length (always possible for a list, but not necessarily for everything you can iterate on). for example, islice(cars, 1, len(cars)-1) will skip the first and last items in the cars list.

提交回复
热议问题