Pergunta

How do I start executing code in a for loop after a certain element in the list has been reached. I've got something that works, but is there a more pythonic or faster way of doing this?

list = ['a', 'b', 'c', 'd', 'e', 'f'] 
condition = 0

for i in list:
    if i == 'c' or condition == 1:
        condition = 1
        print i
Foi útil?

Solução

One way would to be to iterate over a generator combining dropwhile and islice:

from itertools import dropwhile, islice

data = ['a', 'b', 'c', 'd', 'e', 'f'] 
for after in islice(dropwhile(lambda L: L != 'c', data), 1, None):
    print after

If you want including then drop the islice.

Outras dicas

A little simplified code:

lst = ['a', 'b', 'c', 'd', 'e', 'f'] 

start_index = lst.index('c')
for i in lst[start_index:]:
    print i
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top