繁体   English   中英

在Python中向前和向后迭代

[英]Iterating forward and backward in Python

我有一个带有计数器组件的编码接口。 每次更新时,它仅增加1。 考虑一下它是我必须使用的{1,2,3,...}的无限生成器。

我需要使用此值并将其从-1.5迭代到1.5。 因此,迭代应从-1.5开始并达到1.5,然后从1.5返回至-1.5。

如何使用该无限迭代器生成该范围内的迭代?

您可以使用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)

这将重复列表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 ...

就像是:

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

输出:

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

请注意,此操作从1.5开始,因为infGenGiven中的第一个值为0,尽管对于您的生成器而言,它的值为1,所以infGenCycle输出将为您提供所需的内容。

谢谢你们。

我猜最好的方法是使用三角函数( 正弦余弦 ),该函数在正负之一之间振荡。

有关更多详细信息,请访问: https : //en.wikipedia.org/wiki/Trigonometric_functions

干杯

暂无
暂无

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

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