如何在 Python 中获取枚举值
在 Python 中获取枚举中的值:
-
使用点符号访问特定的枚举成员,例如
Color.GREEN
。 -
访问枚举成员的 value 属性,例如
Color.GREEN.value
。
from enum import Enum
class Color(Enum):
RED = 'stop'
GREEN = 'go'
YELLOW = 'get ready'
print(Color.GREEN.value) # 👉️ 'go'
print(Color['GREEN'].value) # 👉️ 'go'
print(Color.RED.value) # 👉️ 'stop'
print(Color['RED'].value) # 👉️ 'stop'
上述代码运行结果如下
我们可以使用枚举成员的名称和值属性来获取枚举的名称和值。
from enum import Enum
class Color(Enum):
RED = 'stop'
GREEN = 'go'
YELLOW = 'get ready'
print(Color.GREEN.value) # 👉️ 'go'
print(Color.GREEN.name) # 👉️ 'GREEN'
我们还可以使用方括号来访问枚举成员。
from enum import Enum
class Color(Enum):
RED = 'stop'
GREEN = 'go'
YELLOW = 'get ready'
name = 'GREEN'
print(Color[name].value) # 👉️ 'go'
print(Color['GREEN'].value) # 👉️ 'go'
当我们提前不知道枚举成员的名称时,这很有用(因为它是从文件中读取或从 API 中获取的)。
我们可以使用列表推导来检查特定值是否在枚举中。
from enum import Enum
class Color(Enum):
RED = 'stop'
GREEN = 'go'
YELLOW = 'get ready'
values = [member.value for member in Color]
print(values) # 👉️ ['stop', 'go', 'get ready']
if 'go' in values:
# 👇️ this runs
print('go is in values')
列表推导用于对每个元素执行一些操作,或者选择满足条件的元素子集。
in
运算符测试成员资格。 例如,如果 x 是 l 的成员,则 x in l 计算结果为 True,否则计算结果为 False。
如果需要遍历枚举,可以使用简单的 for 循环。
from enum import Enum
class Color(Enum):
RED = 'stop'
GREEN = 'go'
YELLOW = 'get ready'
for color in Color:
print(color)
print(color.name, color.value)
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。