我该怎么做;对于每个“,”,从列表的某个索引开始(Python)?

我该怎么做;对于每个“,”,从列表的某个索引开始(Python)?,python,list,Python,List,假设我有以下列表: thelist = ['apple','orange','banana','grapes'] for fruit in thelist: 这将贯穿所有的水果 但是,如果我想从orange开始呢?而不是从苹果开始? 当然,我可以做“如果……继续”,但一定有更好的方法吗?使用python的优雅 for fruit in thelist[1:]: print fruit 使用python的 将从列表中的第二个元素开始 for fruit in thelist[1:]:

假设我有以下列表:

thelist = ['apple','orange','banana','grapes']
for fruit in thelist:
这将贯穿所有的水果

但是,如果我想从orange开始呢?而不是从苹果开始? 当然,我可以做“如果……继续”,但一定有更好的方法吗?

使用python的优雅

for fruit in thelist[1:]:
    print fruit
使用python的

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

for fruit in thelist[1:]:
    ...
将从列表中的第二个元素开始

for fruit in thelist[1:]:
    ...
当然,假设您知道从哪个索引开始。但您可以轻松找到索引:

for fruit in thelist[thelist.index('orange'):]:
    ...
当然,假设您知道从哪个索引开始。但您可以轻松找到索引:

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

切片复制列表,因此如果有许多项,或者如果不想在列表中单独搜索起始索引,迭代器将允许您搜索,然后从那里继续:

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

切片复制列表,因此如果有许多项,或者如果不想在列表中单独搜索起始索引,迭代器将允许您搜索,然后从那里继续:

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

正如Paul McGuire所提到的,切片列表会在内存中创建结果的副本。如果您有一个包含500000个元素的列表,那么执行
l[2://code>将创建一个新的499998元素列表

要避免这种情况,请使用
itertools.islice

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

>>> import itertools

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

正如Paul McGuire所提到的,切片列表会在内存中创建结果的副本。如果您有一个包含500000个元素的列表,那么执行
l[2://code>将创建一个新的499998元素列表

要避免这种情况,请使用
itertools.islice

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

>>> import itertools

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

修正了,但它只是为了概念修正了,但它只是为了概念谢谢你的回答。我很笨,哈哈。我想现在想起来已经太晚了。谢谢你的回答。我很笨,哈哈。我想现在想起来太晚了。您可能想调用“thelist”上的.index而不是“fruit”:)顺便说一句,您可能想调用“thelist”上的.index而不是“fruit”: