Python中的振荡值

2024-05-15 02:41:35 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我需要两个值来回摆动。 第一次说2,第二次说4。从顶部重复。在

所以我写了下面的生成器函数。每次通过next调用它时,它都返回后续值,然后从顶部重复。在

为了学习,为了进步,不是为了意见,还有更好的方法吗?在Python中似乎总有更好的方法,我喜欢学习它们以提高我的技能。在

“主代码”只是为了显示正在使用的发生器、振荡器的示例,而不是振荡器的主要用途。在

## Main code
go_Osci = g_Osci()
for i in xrange(10):
    print("Value: %i") %(go_Osci.next())

## Generator
def g_Osci():
    while True:
        yield 2
        yield 4

Tags: 方法函数代码ingo示例formain
2条回答

在问了这个问题将近两年之后,我想和大家分享一下我最终想出了什么来满足我的需要。使用内联for循环遍历一些交替的值,对于我所需要的,通常过于静态和不灵活。在

我一直回到我的生成器解决方案,因为它在我的应用程序中被证明更加灵活,我可以在我的脚本中随时随地调用next()。在

然后我偶然发现在我的生成器中使用了cycle。通过在实例开始时用所需值的列表“启动”生成器,我可以根据需要在脚本中的任何地方访问交替值。我还可以根据需要使用不同的值来“初始化”更多实例。在

另一个好处是底层代码是通用的,因此可以作为一个可导入的模块来处理。在

我把这种用发电机产生交变值的结构称为“振荡器”

我希望这对将来的人有好处。在

Python 2.7.10

    # Imports #
from __future__ import print_function
from itertools import cycle

    # Generators
def g_Oscillator(l_Periods):
"""Takes LIST and primes gen, then yields VALUES from list as each called/next()"""
g_Result = cycle(l_Periods)
for value in g_Result:
    yield value

    # Main Code
go_52Oscillator = g_Oscillator([5, 2]) ## Primed Ocscillator
go_34Oscillator = g_Oscillator([3, 4]) ## Primed Ocscillator
go_ABCOscillator = g_Oscillator(["A", "B", "C"]) ## Primed Ocscillator
for i in xrange(5):
    print(go_34Oscillator.next())
print()

for i in xrange(5):
    print(go_52Oscillator.next())
print()

for i in xrange(5):
    print(go_ABCOscillator.next())

是的,还有更好的办法。^{}是为此任务显式设计的:

>>> from itertools import cycle
>>> for i in cycle([2, 4]):
...     print i
...
2
4
2
4
2
4
2
# Goes on forever

也可以使用^{}只循环一定次数:

^{pr2}$

相关问题 更多 >

    热门问题