在python中如何跳过第一个for循环?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (2195)

在python中,我如何做这样的事情:

for car in cars:
   # Skip first and last, do work for rest
提问于
用户回答回答于

对于任何可迭代项,跳过第一项:

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

如果您想跳过最后一步,您可以:

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'
用户回答回答于

要跳过Python中的第一个元素,只需编写

for car in cars[1:]:
    # Do What Ever you want

或者跳过最后一个

for car in cars[:-1]:
    # Do What Ever you want

您可以对任何序列使用这个概念。

扫码关注云+社区

领取腾讯云代金券