开发者

How do I do a "for each" , starting at a certain index of a list (Python)?

Suppose I have this list:

thelist = ['apple','orange','banana','grapes']
for fruit in thelist:

This would go throug开发者_如何学运维h all the fruits.

However, what if I wanted to start at orange? Instead of starting at apple? Sure, I could do "if ...continue", but there must be a better way?


for fruit in thelist[1:]:
    ...

this of course suppose you know at which index to start. but you can find the index easily:

for fruit in thelist[thelist.index('orange'):]:
    ...


using python's elegant slices

>>> for fruit in thelist[1:]:
>>>    print fruit


As mentioned by Paul McGuire, slicing a list creates a copy in memory of the result. If you have a list with 500,000 elements then doing l[2:] is going to create a new 499,998 element list.

To avoid this, use itertools.islice:

>>> thelist = ['a', 'b', 'c']

>>> import itertools

>>> for i in itertools.islice(thelist, 1, None):
...     print i
...
b
c


for fruit in thelist [1:]:

will start at the second element in the list.


for fruit in thelist[1:]:
    print fruit


Slices make copies of lists, so if there are many items, or if you don't want to separately search the list for the starting index, an iterator will let you search, and then continue from there:

>>> thelist = ['apple','orange','banana','grapes']
>>> fruit_iter = iter(thelist)
>>> target_value = 'orange'
>>> while fruit_iter.next() != target_value: pass
...
>>> # at this point, fruit_iter points to the entry after target_value
>>> print ','.join(fruit_iter)
banana,grapes
>>>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜