简体   繁体   English

我如何从列表的某个索引(Python)开始做“ for each”?

[英]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 through 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 使用python的优雅切片

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

As mentioned by Paul McGuire, slicing a list creates a copy in memory of the result. 如Paul McGuire所述,切片列表会创建一个副本,以存储结果。 If you have a list with 500,000 elements then doing l[2:] is going to create a new 499,998 element list. 如果您有一个包含500,000个元素的列表,那么执行l[2:]将创建一个新的499,998个元素列表。

To avoid this, use itertools.islice : 为了避免这种情况,请使用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:]:

从列表中的第二个元素开始。

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
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM