Skip first entry in for loop in python?

前端 未结 13 2462
面向向阳花
面向向阳花 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:15

    The more_itertools project extends itertools.islice to handle negative indices.

    Example

    import more_itertools as mit
    
    iterable = 'ABCDEFGH'
    list(mit.islice_extended(iterable, 1, -1))
    # Out: ['B', 'C', 'D', 'E', 'F', 'G']
    

    Therefore, you can elegantly apply it slice elements between the first and last items of an iterable:

    for car in mit.islice_extended(cars, 1, -1):
        # do something
    

提交回复
热议问题