本文介绍了迭代列表的一部分的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])
:
import itertools
for line in itertools.islice(list , start, stop):
foo(line)
这篇关于迭代列表的一部分的pythonic方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!