跳过python中的for循环中的第一个条目?

问题:跳过python中的for循环中的第一个条目?

在python中,我该怎么做:

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

In python, How do I do something like:

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

回答 0

其他答案仅适用于序列。

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

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'

The other answers only work for a sequence.

For any iterable, to skip the first item:

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

If you want to skip the last, you could do:

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'

回答 1

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

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

或跳过最后一个元素

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

您可以将此概念用于任何序列。

To skip the first element in Python you can simply write

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

or to skip the last elem

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

You can use this concept for any sequence.


回答 2

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

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

在这种情况下,使用起点1和终点None调用islice,表示迭代器的结束。

为了能够从可迭代对象的末尾跳过项目,您需要知道其长度(对于列表而言总是可能的,但不一定可以迭代的所有内容)。例如,islice(cars,1,len(cars)-1)将跳过汽车列表中的第一项和最后一项。

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.


回答 3

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

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]

Here is a more general generator function that skips any number of items from the beginning and end of an iterable:

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()

Example usage:

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

回答 4

for item in do_not_use_list_as_a_name[1:-1]:
    #...do whatever
for item in do_not_use_list_as_a_name[1:-1]:
    #...do whatever

回答 5

基于@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

Based on @SvenMarnach ‘s Answer, but bit simpler and without using deque

>>> 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]

Also Note, based on my timeit result, this is marginally faster than the deque solution

>>> 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

回答 6

例:

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

在从0开始的python索引中,我们可以使用切片运算符在迭代中进行操作。

for i in range(1,-1):

Example:

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):

回答 7

好吧,您的语法并不是真正的Python。

Python中的迭代遍历容器的内容(从技术上讲,遍历迭代器),并带有一个语法for item in container。在这种情况下,容器是cars列表,但是您要跳过第一个和最后一个元素,因此意味着cars[1:-1](python列表是从零开始的,负数从末开始计数,并且:是对语法进行切片。

所以你要

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

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

回答 8

替代方法:

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

An alternative method:

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

回答 9

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

从…来:

for item in my_items:
  do_something(item)

至:

for i, item in enumerate(my_items):
  if i == 0:
    continue
  do_something(item)

Here’s my preferred choice. It doesn’t require adding on much to the loop, and uses nothing but built in tools.

Go from:

for item in my_items:
  do_something(item)

to:

for i, item in enumerate(my_items):
  if i == 0:
    continue
  do_something(item)

回答 10

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

for car in cars[1:-1]:
    pass

If cars is a sequence you can just do

for car in cars[1:-1]:
    pass

回答 11

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']

因此,您可以将它的slice元素优雅地应用于iterable的第一项和最后一项之间:

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

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

回答 12

我看起来是这样的,即使它看起来像个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

I do it like this, even though it looks like a hack it works every time:

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