Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

python - pythonic way to iterate over part of a list

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.

I can do this:

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

But, that's just gross.

Better might be this:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...