Skip first entry in for loop in python?

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

    Well, your syntax isn't really Python to begin with.

    Iterations in Python are over he contents of containers (well, technically it's over iterators), with a syntax for item in container. In this case, the container is the cars list, but you want to skip the first and last elements, so that means cars[1:-1] (python lists are zero-based, negative numbers count from the end, and : is slicing syntax.

    So you want

    for c in cars[1:-1]:
        do something with c
    

提交回复
热议问题