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

7

我在Python中有一个星期几的枚举:

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]

我尝试了所有方法,但都没有返回enum的值(例如:days_of_the_week[1] >>> 'tuesday')。

有什么方法可以实现吗?


你需要一个类吗?这是一个任务吗?因为你可以很容易地使用字典得到你想要的东西。 - MSH
@MSH 这不是一项任务,我只是在探索Python。 - Sara Briccoli
2
被标记为重复的问题是关于C#而不是Python的。 - qwr
4个回答

8

如果我理解正确,您想要做的是:

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'

3

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

然而,你根本不需要写那个。Python已经提供了这个功能。

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

3
另一种简单的方法是:
list(days_of_the_weeks)[index]

它将返回Enum类中的元素。如果您想获取其值:
list(days_of_the_weeks)[index].value

Python语言是否保证了顺序,还是说这仅仅是一个可能在未来发生变化的实现细节? - Newbyte
它由枚举库保证。来自https://docs.python.org/3/library/enum.html: "可以迭代以按定义顺序返回其规范(即非别名)成员"。 - undefined

1

对于星期几,Python拥有内置的日历模块,但如果这只是一个示例,这是一种方法。

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

  @property
  def index(self):
    return list(days_of_the_week).index(self)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接