Skip multiple iterations in loop python -


i have list in loop , want skip 3 elements after look has been reached. in this answer couple of suggestions made fail make use of them:

song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life'] sing in song:     if sing == 'look':         print sing         continue         continue         continue         continue         print 'a' + sing     print sing 

four times continue nonsense of course , using 4 times next() doesn't work.

the output should like:

always aside of life 

for uses iter(song) loop; can in own code , advance iterator inside loop; calling iter() on iterable again return same iterable object can advance iterable inside loop for following right along in next iteration.

advance iterator next() function; works correctly in both python 2 , 3 without having adjust syntax:

song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life'] song_iter = iter(song) sing in song_iter:     print sing     if sing == 'look':         next(song_iter)         next(song_iter)         next(song_iter)         print 'a' + next(song_iter) 

by moving print sing line can avoid repeating ourselves too.

using next() way can raise stopiteration exception, if iterable out of values.

you catch exception, it'd easier give next() second argument, default value ignore exception , return default instead:

song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life'] song_iter = iter(song) sing in song_iter:     print sing     if sing == 'look':         next(song_iter, none)         next(song_iter, none)         next(song_iter, none)         print 'a' + next(song_iter, '') 

i'd use itertools.islice() skip 3 elements instead; saves repeated next() calls:

from itertools import islice  song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life'] song_iter = iter(song) sing in song_iter:     print sing     if sing == 'look':         print 'a' + next(islice(song_iter, 3, 4), '') 

the islice(song_iter, 3, 4) iterable skip 3 elements, return 4th, done. calling next() on object retrieves 4th element song_iter().

demo:

>>> itertools import islice >>> song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life'] >>> song_iter = iter(song) >>> sing in song_iter: ...     print sing ...     if sing == 'look': ...         print 'a' + next(islice(song_iter, 3, 4), '') ...  aside of life 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -