简体   繁体   English

在Python中向前和向后迭代

[英]Iterating forward and backward in Python

I have a coding interface which has a counter component. 我有一个带有计数器组件的编码接口。 It simply increments by 1 with every update. 每次更新时,它仅增加1。 Consider it an infinite generator of {1,2,3,...} over time which I HAVE TO use. 考虑一下它是我必须使用的{1,2,3,...}的无限生成器。

I need to use this value and iterate from -1.5 to 1.5. 我需要使用此值并将其从-1.5迭代到1.5。 So, the iteration should start from -1.5 and reach 1.5 and then from 1.5 back to -1.5. 因此,迭代应从-1.5开始并达到1.5,然后从1.5返回至-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. 您可以使用itertools cycle重复序列。

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 : 这将重复列表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. 请注意,此操作从1.5开始,因为infGenGiven中的第一个值为0,尽管对于您的生成器而言,它的值为1,所以infGenCycle输出将为您提供所需的内容。

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 有关更多详细信息,请访问: https : //en.wikipedia.org/wiki/Trigonometric_functions

Cheers 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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