231

在 python 中,我该怎么做:

for car in cars:
   # Skip first and last, do work for rest
4

13 回答 13

453

要跳过 Python 中的第一个元素,您可以简单地编写

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

或跳过最后一个元素

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

您可以将此概念用于任何sequenceiterable但不能用于任何)。

于 2012-04-09T20:16:57.183 回答
309

其他答案仅适用于序列。

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

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'
于 2012-04-09T20:17:58.137 回答
41

跳过第一项的最佳方法是:

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

islice在这种情况下,用 的起点1和 的终点调用None,表示 的结束iterable

为了能够从iterable. 例如,islice(cars, 1, len(cars)-1)将跳过cars.

于 2012-10-16T09:23:05.857 回答
29

这是一个更通用的生成器函数,它从可迭代的开头和结尾跳过任意数量的项目:

def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    for x in itertools.islice(it, at_start):
        pass
    queue = collections.deque(itertools.islice(it, at_end))
    for x in it:
        queue.append(x)
        yield queue.popleft()

示例用法:

>>> list(skip(range(10), at_start=2, at_end=2))
[2, 3, 4, 5, 6, 7]
于 2012-04-09T21:06:32.293 回答
11
for item in list_name[1:-1]:
    #...do whatever
于 2012-04-09T20:16:50.097 回答
6

例子:

mylist=['one','two','three','four','five']
for i in mylist[1:]:
   print(i)

In python index start from 0, We can use slicing operator to make manipulations in iteration.

for i in range(1,-1):
于 2019-11-16T09:42:39.007 回答
4

这是我的首选。它不需要在循环中添加太多内容,并且只使用内置工具。

从...来:

for item in my_items:
  do_something(item)

到:

for i, item in enumerate(my_items):
  if i == 0:
    continue
  do_something(item)
于 2019-06-28T22:41:03.880 回答
3

好吧,您的语法一开始就不是真正的 Python。

Python 中的迭代在容器的内容之上(嗯,从技术上讲,它在迭代器之上),语法为for item in container. 在这种情况下,容器是cars列表,但您想跳过第一个和最后一个元素,这意味着cars[1:-1](python 列表是从零开始的,负数从末尾开始计数,并且:是切片语法。

所以你要

for c in cars[1:-1]:
    do something with c
于 2012-04-09T20:22:52.677 回答
2

基于@SvenMarnach 的答案,但更简单且不使用双端队列

>>> def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    it = itertools.islice(it, at_start, None)
    it, it1 = itertools.tee(it)
    it1 = itertools.islice(it1, at_end, None)
    return (next(it) for _ in it1)

>>> list(skip(range(10), at_start=2, at_end=2))
[2, 3, 4, 5, 6, 7]
>>> list(skip(range(10), at_start=2, at_end=5))
[2, 3, 4]

另请注意,根据我的timeit结果,这比双端队列解决方案略快

>>> iterable=xrange(1000)
>>> stmt1="""
def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    it = itertools.islice(it, at_start, None)
    it, it1 = itertools.tee(it)
    it1 = itertools.islice(it1, at_end, None)
    return (next(it) for _ in it1)
list(skip(iterable,2,2))
    """
>>> stmt2="""
def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    for x in itertools.islice(it, at_start):
        pass
    queue = collections.deque(itertools.islice(it, at_end))
    for x in it:
        queue.append(x)
        yield queue.popleft()
list(skip(iterable,2,2))
        """
>>> timeit.timeit(stmt = stmt1, setup='from __main__ import iterable, skip, itertools', number = 10000)
2.0313770640908047
>>> timeit.timeit(stmt = stmt2, setup='from __main__ import iterable, skip, itertools, collections', number = 10000)
2.9903135454296716
于 2013-09-16T20:21:44.167 回答
1

如果cars是一个序列,你可以这样做

for car in cars[1:-1]:
    pass
于 2012-04-09T20:17:17.673 回答
1

另一种方法:

for idx, car in enumerate(cars):
    # Skip first line.
    if not idx:
        continue
    # Skip last line.
    if idx + 1 == len(cars):
        continue
    # Real code here.
    print car
于 2014-07-18T16:13:35.787 回答
1

more_itertools项目扩展itertools.islice到处理负指数。

例子

import more_itertools as mit

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

因此,您可以优雅地在可迭代的第一项和最后一项之间应用它切片元素:

for car in mit.islice_extended(cars, 1, -1):
    # do something
于 2017-06-13T22:57:20.893 回答
-1

我是这样做的,尽管它看起来像一个 hack,但它每次都有效:

ls_of_things = ['apple', 'car', 'truck', 'bike', 'banana']
first = 0
last = len(ls_of_things)
for items in ls_of_things:
    if first == 0
        first = first + 1
        pass
    elif first == last - 1:
        break
    else:
        do_stuff
        first = first + 1
        pass
于 2016-12-20T16:20:29.643 回答