遍历列表一部分的pythonic方法 [英] pythonic way to iterate over part of a list

查看:109
本文介绍了遍历列表一部分的pythonic方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

You can try itertools.islice(iterable[, start], stop[, step]):

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

这篇关于遍历列表一部分的pythonic方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆