如何从python枚举类中获取所有值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29503339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get all values from python enum class?
提问by user1159517
I'm using Enum4 library to create an enum class as follows:
我正在使用 Enum4 库创建一个枚举类,如下所示:
class Color(Enum):
RED = 1
BLUE = 2
I want to print [1, 2]
as a list somewhere. How can I achieve this?
我想在[1, 2]
某处打印为列表。我怎样才能做到这一点?
采纳答案by Marcin
回答by ozgur
You can do the following:
您可以执行以下操作:
[e.value for e in Color]
回答by vlad-ardelean
So the Enum
has a __members__
dict.
The solution that @ozgur proposed is really the best, but you can do this, which does the same thing, with more work
所以Enum
有一个__members__
字典。@ozgur 提出的解决方案确实是最好的,但你可以这样做,它做同样的事情,做更多的工作
[color.value for color_name, color in Color.__members__.items()]
[color.value for color_name, color in Color.__members__.items()]
The __members__
dictionary could come in handy if you wanted to insert stuff dynamically in it... in some crazy situation.
__members__
如果您想在其中动态插入内容,字典可能会派上用场……在某些疯狂的情况下。
[EDIT]Apparently __members__
is not a dictionary, but a map proxy. Which means you can't easily add items to it.
[编辑]显然__members__
不是字典,而是地图代理。这意味着您不能轻松地向其中添加项目。
You can however do weird stuff like MyEnum.__dict__['_member_map_']['new_key'] = 'new_value'
, and then you can use the new key like MyEnum.new_key
.... but this is just an implementation detail, and should not be played with. Black magic is payed for with huge maintenance costs.
然而,你可以做一些奇怪的事情,比如MyEnum.__dict__['_member_map_']['new_key'] = 'new_value'
,然后你可以使用新的键,比如MyEnum.new_key
.... 但这只是一个实现细节,不应该被玩。黑魔法的代价是巨大的维护成本。
回答by Jeff
To use Enum with any type of value, try this:
Updated with some improvements... Thanks @Jeff, by your tip!
要将 Enum 与任何类型的值一起使用,请尝试以下操作:
更新了一些改进...谢谢@Jeff,给您提示!
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 'GREEN'
BLUE = ('blue', '#0000ff')
@staticmethod
def list():
return list(map(lambda c: c.value, Color))
print(Color.list())
As result:
结果:
[1, 'GREEN', ('blue', '#0000ff')]
回答by Meysam Azad
class enum.Enum
is a class that solves all your enumeration needs, so you just need to inherit from it, and add your own fields. Then from then on, all you need to do is to just call it's attributes: name
& value
:
classenum.Enum
是一个解决你所有枚举需求的类,所以你只需要继承它,并添加你自己的字段。从那时起,您需要做的就是调用它的属性:name
& value
:
from enum import Enum
class Letter(Enum):
A = 1
B = 2
C = 3
print({i.name: i.value for i in Letter})
# prints {'A': 1, 'B': 2, 'C': 3}
回答by blueFast
Based on the answer by @Jeff, refactored to use a classmethod
so that you can reuse the same code for any of your enums:
根据@Jeff 的回答,重构为使用 aclassmethod
以便您可以对任何枚举重用相同的代码:
from enum import Enum
class ExtendedEnum(Enum):
@classmethod
def list(cls):
return list(map(lambda c: c.value, cls))
class OperationType(ExtendedEnum):
CREATE = 'CREATE'
STATUS = 'STATUS'
EXPAND = 'EXPAND'
DELETE = 'DELETE'
print(OperationType.list())
Produces:
产生:
['CREATE', 'STATUS', 'EXPAND', 'DELETE']
回答by Ali Shekari
you can use iter() function:
您可以使用 iter() 函数:
from enum import IntEnum
class Color(IntEnum):
RED = 1
BLUE = 2
l=[]
for i in iter(Color):
l.append(i.value)
print(l)
回答by EliuX
Use _member_names_
for a quick easy result if it is just the names, i.e.
使用_member_names_
一种快速简单的结果,如果它仅仅是个名字,即
Color._member_names_
Also, you have _member_map_
which returns an ordered dictionary of the elements. This function returns a collections.OrderedDict
, so you have Color._member_names_.items()
and Color._member_names_.values()
to play with. E.g.
此外,您还拥有_member_map_
返回元素的有序字典。此函数返回 a collections.OrderedDict
,因此您可以使用Color._member_names_.items()
和Color._member_names_.values()
。例如
return list(map(lambda x: x.value, Color._member_map_.values()))
will return all the valid values of Color
将返回 Color 的所有有效值