Rho*_*bus 3 enums loops python-3.x
我有一个可存储4个季节的枚举类,希望能够移至下一个季节。当我到达结尾(秋天)时,我希望它回到第一个(冬天)。有没有一种简单的方法可以做到这一点,还是我最好只使用列表或其他结构。我在网上发现的一些答案似乎有点过头了,所以我很好奇使用枚举是否值得。
from enum import Enum, auto
class Season(Enum):
WINTER = auto()
SPRING = auto()
SUMMER = auto()
FALL = auto()
Run Code Online (Sandbox Code Playgroud)
>>> season = Season.SUMMER
>>> season.next()
<Season.FALL: 4>
>>> season.next()
<Season.WINTER: 1>
Run Code Online (Sandbox Code Playgroud)
由于Enum已经支持迭代协议,因此使用起来非常简单itertools.cycle:
>>> from itertools import cycle
>>> seasons = cycle(Season)
>>> next(seasons)
<Season.WINTER: 1>
>>> next(seasons)
<Season.SPRING: 2>
>>> next(seasons)
<Season.SUMMER: 3>
>>> next(seasons)
<Season.FALL: 4>
>>> next(seasons)
<Season.WINTER: 1>
Run Code Online (Sandbox Code Playgroud)