Python:如何在两个值之间切换 [英] Python: How to toggle between two values

查看:43
本文介绍了Python:如何在两个值之间切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Python 中的两个值之间切换,即在 0 和 1 之间.

I want to toggle between two values in Python, that is, between 0 and 1.

例如,当我第一次运行一个函数时,它产生数字 0.下一次,它产生 1.第三次它回到零,依此类推.

For example, when I run a function the first time, it yields the number 0. Next time, it yields 1. Third time it's back to zero, and so on.

对不起,如果这没有意义,但有人知道这样做的方法吗?

Sorry if this doesn't make sense, but does anyone know a way to do this?

推荐答案

使用 itertools.cycle():

from itertools import cycle
myIterator = cycle(range(2))

myIterator.next()   # or next(myIterator) which works in Python 3.x. Yields 0
myIterator.next()   # or next(myIterator) which works in Python 3.x. Yields 1
# etc.

请注意,如果您需要比 [0, 1] 更复杂的循环,此解决方案将比此处发布的其他解决方案更具吸引力...

Note that if you need a more complicated cycle than [0, 1], this solution becomes MUCH more attractive than the other ones posted here...

from itertools import cycle
mySmallSquareIterator = cycle(i*i for i in range(10))
# Will yield 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 0, 1, 4, ...

这篇关于Python:如何在两个值之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆