如何从列表的某个索引(Python)开始为每个人做一个"for each"?

TIM*_*MEX 1 python list

假设我有这个列表:

thelist = ['apple','orange','banana','grapes']
for fruit in thelist:
Run Code Online (Sandbox Code Playgroud)

这将贯穿所有成果.

但是,如果我想从橙色开始怎么办?而不是从苹果开始?当然,我可以做"如果......继续",但必须有更好的方法吗?

Adr*_*son 14

for fruit in thelist[1:]:
    ...
Run Code Online (Sandbox Code Playgroud)

这当然假设您知道要从哪个索引开始.但你可以很容易地找到索引:

for fruit in thelist[thelist.index('orange'):]:
    ...
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句.你可能想在"thelist"而不是"fruit"上调用.index :) (3认同)

tos*_*osh 11

使用python的优雅切片

>>> for fruit in thelist[1:]:
>>>    print fruit
Run Code Online (Sandbox Code Playgroud)