简体   繁体   中英

Iterating forward and backward in Python

I have a coding interface which has a counter component. It simply increments by 1 with every update. Consider it an infinite generator of {1,2,3,...} over time which I HAVE TO use.

I need to use this value and iterate from -1.5 to 1.5. So, the iteration should start from -1.5 and reach 1.5 and then from 1.5 back to -1.5.

How should I use this infinite iterator to generate an iteration in that range?

You can use cycle from itertools to repeat a sequence.

from itertools import cycle

# build the list with 0.1 increment
v = [(x-15)/10 for x in range(31)]
v = v + list(reversed(v))
cv = cycle(v)

for c in my_counter:
    x = next(cv)

This will repeat the list v :

 -1.5, -1.4, -1.3, -1.2, -1.1, -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, 
 -0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0,
 1.1, 1.2, 1.3, 1.4, 1.5, 1.5, 1.4, 1.3, 1.2, 1.1, 1.0, 0.9, 0.8, 0.7, 
 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0, -0.1, -0.2, -0.3, -0.4, -0.5, -0.6, 
 -0.7, -0.8, -0.9, -1.0, -1.1, -1.2, -1.3, -1.4, -1.5, -1.5, -1.4, -1.3, 
 -1.2, -1.1, -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 
 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 
 1.4, 1.5, 1.5, 1.4, 1.3, 1.2, 1.1, 1.0, 0.9 ...

Something like:

import itertools

infGenGiven = itertools.count() # This is similar your generator

def func(x):
    if x%2==0:
        return 1.5
    else:
        return -1.5

infGenCycle = itertools.imap(func, infGenGiven)

count=0
while count<10:
    print infGenCycle.next()
    count+=1

Output:

1.5
-1.5
1.5
-1.5
1.5
-1.5
1.5
-1.5
1.5
-1.5

Note that this starts 1.5 because the first value in infGenGiven is 0, although for your generator it is 1 and so the infGenCycle output will give you what you want.

Thank you all.

I guess the best approach is to use the trigonometric functions ( sine or cosine ) which oscillate between plus and minus one.

More details at: https://en.wikipedia.org/wiki/Trigonometric_functions

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM