Here are some examples to easily convert Enum to a list/array of int, str, or Enum AND be able to sort.
import numpy as np
class Color[int,Enum]:
YELLOW = 3
RED = 1
BLUE = 2
print['1]:',list[Color]]
print['2]:',np.array[list[Color]]] ## int64 [8 bytes]
print['3]:',sorted[np.array[Color, dtype=str]]]
print['4]:',np.array[sorted[Color], dtype=object]]
print['5]:',np.array[sorted[Color], dtype=np.int8]] # 1 byte
print['6]:',np.array[sorted[Color, key=lambda x: -x.value], dtype=np.int8]]
print['7]:',np.array[sorted[Color, key=lambda x: str[x]], dtype=np.int8]]
class Color[tuple,Enum]:
YELLOW = [3,3]
RED = [1,1]
BLUE = [2,2]
print['8]:',np.array[sorted[Color]]]
print['9]:',list[map[tuple,sorted[Color, key=lambda x: -x[1]]]]]
Output:
1]: [, , ]
2]: [3 1 2]
3]: ['Color.BLUE', 'Color.RED', 'Color.YELLOW']
4]: [ ]
5]: [1 2 3]
6]: [3 2 1]
7]: [2 1 3]
8]: [[1 1]
[2 2]
[3 3]]
9]: [[3, 3], [2, 2], [1, 1]]
Get a list of all Enum values in Python #
Use a list comprehension to get a list of all enum values, e.g. values = [member.value for member in Sizes]
. On each iteration, access the value
attribute on the enum member to get a list of all of the enum's values.
Copied!
from enum import Enum class Sizes[Enum]: SMALL = 1 MEDIUM = 2 LARGE = 3 values = [member.value for member in Sizes] print[values] # 👉️ [1, 2, 3] names = [member.name for member in Sizes] print[names] # 👉️ ['SMALL', 'MEDIUM', 'LARGE']
List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.
In the first example, we created a list containing all of the values in the enum.
In the second example, we used the name
attribute to create a list containing all of the names in the enum.
Copied!
from enum import Enum class Sizes[Enum]: SMALL = 1 MEDIUM = 2 LARGE = 3 print[Sizes.SMALL.name] # 👉️ SMALL print[Sizes.SMALL.value] # 👉️ 1
You can use the same approach if you need to get a list of tuples containing the name and value of each enum member.
Copied!
from enum import Enum class Sizes[Enum]: SMALL = 1 MEDIUM = 2 LARGE = 3 result = [[member.name, member.value] for member in Sizes] # 👇️ [['SMALL', 1], ['MEDIUM', 2], ['LARGE', 3]] print[result]
The first element in each tuple is the name, and the second - the value of the enum member.
Use the in
operator if you need to check if a value is in an enum.
Copied!
from enum import Enum class Sizes[Enum]: SMALL = 1 MEDIUM = 2 LARGE = 3 values = [member.value for member in Sizes] print[values] # 👉️ [1, 2, 3] if 2 in values: # 👇️ this runs print['2 is in values']
The in operator tests for membership. For example, x in l
evaluates to True
if x
is a member of l
, otherwise it evaluates to False
.
You can also use a simple
for
loop if you need to iterate over an enum.
Copied!
from enum import Enum class Sizes[Enum]: SMALL = 1 MEDIUM = 2 LARGE = 3 for size in Sizes: print[size] print[size.name, size.value]