Python: cycle through elements in list reversing when the end is reached -


i have list looks like:

a = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10'] 

i need cycle through list 1 element @ time when end of list reached, cycle needs reversed.

for example, using itertools.cycle:

from itertools import cycle a_cycle = cycle(a) _ in range(30):     print a_cycle.next() 

i get:

01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10 

but need is:

01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 10, 09, 08, 07, 06, 05, 04, 03, 02, 01, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10 

i need cycle through a fixed number of times, 200.

you can cycle chain of a , reversed a, eg:

from itertools import cycle, islice, chain  = range(1, 11) b = reversed(a) c = cycle(chain(a, b)) d = list(islice(c, 100)) # `c` infinite - hence `islice` stop @ point... 

which gives you:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 

note: if a exhaustable iterator, need make copy of a first. given example, fine.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -