【问题标题】:Is there a simple method for circularly iterating over an enum?是否有一种简单的方法可以循环迭代枚举?
【发布时间】:2020-03-18 15:43:36
【问题描述】:

我有一个存储 4 个季节的枚举类,并且希望能够移动到下一个季节。当我到达终点(秋季)时,我希望它回到第一个(冬季)。有没有一种简单的方法可以做到这一点,或者我最好只使用列表或其他结构。我在网上找到的一些答案似乎有点矫枉过正,所以我很好奇使用枚举是否值得。

from enum import Enum, auto

class Season(Enum):
    WINTER = auto()
    SPRING = auto()
    SUMMER = auto()
    FALL   = auto()
>>> season = Season.SUMMER
>>> season.next()
<Season.FALL: 4>
>>> season.next()
<Season.WINTER: 1>

【问题讨论】:

    标签: python-3.x loops enums


    【解决方案1】:

    由于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>
    

    【讨论】:

    猜你喜欢
    • 2020-02-07
    • 2011-12-29
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 2010-09-17
    • 2022-06-11
    相关资源
    最近更新 更多