Python - 如何通过索引获取枚举值

Python - How to get Enum value by index

我在 Python 有一个 days_of_the 周的枚举:

class days_of_the_week(str, Enum):
  monday = 'monday'
  tuesday = 'tuesday'
  wednesday = 'wednesday'
  thursday = 'thursday'
  friday = 'friday'
  saturday = 'saturday'
  sunday = 'sunday'

我想使用索引访问值。

我试过:

days_of_the_week.value[index]
days_of_the_week[index].value
days_of_the_week.values()[index]

等等... 但是我尝试的一切都没有给我返回枚举的价值 (例如 days_of_the_week[1] >>> 'tuesday')

有办法吗?

这些只是字符串常量。他们没有“索引”,不能以这种方式引用。

然而,你根本不需要写那个。 Python 提供。

>>> import calendar
>>> list(calendar.day_name)
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
>>> calendar.day_name[5]
'Saturday'
>>> 

IIUC,你想做的事情:

from enum import Enum

class days_of_the_week(Enum):
    monday = 0
    tuesday = 1
    wednesday = 2
    thursday = 3
    friday = 4
    saturday = 5
    sunday = 6

>>> days_of_the_week(1).name
'tuesday'