擅长:python、mysql、java
<p>在问了这个问题将近两年之后,我想和大家分享一下我最终想出了什么来满足我的需要。使用内联<code>for</code>循环遍历一些交替的值,对于我所需要的,通常过于静态和不灵活。在</p>
<p>我一直回到我的生成器解决方案,因为它在我的应用程序中被证明更加灵活,我可以在我的脚本中随时随地调用<code>next()</code>。在</p>
<p>然后我偶然发现在我的生成器中使用了<code>cycle</code>。通过在实例开始时用所需值的列表“启动”生成器,我可以根据需要在脚本中的任何地方访问交替值。我还可以根据需要使用不同的值来“初始化”更多实例。在</p>
<p>另一个好处是底层代码是通用的,因此可以作为一个可导入的模块来处理。在</p>
<p>我把这种用发电机产生交变值的结构称为“振荡器”</p>
<p>我希望这对将来的人有好处。在</p>
<p>Python 2.7.10</p>
<pre><code> # 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())
</code></pre>