python - Python 中的振荡值

标签 python python-2.7 cycle

所以我需要让 2 个值来回摆动。 第一次说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

最佳答案

是的,有更好的方法。 itertools.cycle专为这项任务而设计:

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

您还可以使用 enumerate只循环一定次数:

>>> for i, j in enumerate(cycle([2, 4])):
...     if i == 10:  # Only loop 10 times
...         break
...     print j
...
2
4
2
4
2
4
2
4
2
4
>>>

关于python - Python 中的振荡值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27336417/

相关文章:

algorithm - 如何找到经过特定源节点的最负权重循环的路径?

algorithm - 如果任何节点最多有 2 条边,则找出是否形成循环的更快方法?

python - 如何合并pandas中的两个数据框?

python - AWS Lambda 运行在 Windows 中创建的 zip 包

python - 选择第一个下拉列表后,第二个下拉列表发生变化

python-2.7 - Pyasn1 decoder.decode 是如何工作的?

Python - 从字符串解析 IPv4 地址(即使被审查)

python - 删除最后 3 个版本文件夹 - Python

Python3 beautifulsoup模块 'NoneType'错误