Let us assume that we have an enum class:
class MyEnum(Enum):
foo = 1
bar = 2
How to get the list of values [1, 1, 2]
from the above list of enumerations?
mylist = [MyEnum.foo, MyEnum.foo, MyEnum.bar]
I know it is possible to create a new list using list comprehension, but I am wondering if there exists a more natural and straighforward way to get the same output.
CodePudding user response:
I could only think about a map:
myvaluelist = list(map(lambda _ : _.value, mylist))
however I think it is much less 'natural' than list comprehesion:
myvaluelist = [_.value for _ in mylist]
[EDIT] Also comprehesions are quite well optimized, which may be another plus, once one is used to them.
CodePudding user response:
we can access name
and value
of an Enum
class by .name
, .value
. So a simple list comprehension could solve your problem.
class MyEnum(Enum):
foo = 1
bar = 2
mylist = [MyEnum.foo, MyEnum.foo, MyEnum.bar]
my_enum_val_list = [i.value for i in mylist]