迭代列表的一部分的pythonic方法

2022-01-24 00:00:00 python list iteration

问题描述

我想遍历列表中除前几个元素之外的所有内容,例如:

I want to iterate over everything in a list except the first few elements, e.g.:

for line in lines[2:]:
    foo(line)

这很简洁,但会复制整个列表,这是不必要的.我可以这样做:

This is concise, but copies the whole list, which is unnecessary. I could do:

del lines[0:2]
for line in lines:
    foo(line)

但这会修改​​列表,这并不总是好的.

But this modifies the list, which isn't always good.

我可以这样做:

for i in xrange(2, len(lines)):
    line = lines[i]
    foo(line)

但是,这太恶心了.

可能会更好:

for i,line in enumerate(lines):
    if i < 2: continue
    foo(line)

但它不像第一个例子那么明显.

But it isn't quite as obvious as the very first example.

那么:有什么方法可以做到与第一个示例一样明显,但又不会不必要地复制列表?

So: What's a way to do it that is as obvious as the first example, but doesn't copy the list unnecessarily?


解决方案

你可以试试itertools.islice(iterable[, start], stop[, step]):

import itertools
for line in itertools.islice(list , start, stop):
     foo(line)

相关文章