Home > Mobile >  Rewriting data inside a list by enum values
Rewriting data inside a list by enum values

Time:07-06

Let's say i have an enum that looks like this:

class MyEnum(str, Enum):
    A = 'atk'
    C = 'ccc'
    B = 'break'

And a list looking like so:

list = ['A', 123, 'B', 44, 2, 'C']

How do i make it that the A B and C in array are changed by its Enum values and look something like that?

list = ['atk', 123, 'break', 44, 2, 'ccc']

CodePudding user response:

You can try whether each list element is an enum value (see, e.g., How to test if an Enum member with a certain name exists?) and just replace the value in this case:

def replace(x):
    try:
        return MyEnum[x].value
    except KeyError:
        return x
        
list = [replace(x) for x in list]

Try it online here.

CodePudding user response:

Try:

from enum import Enum


class MyEnum(str, Enum):
    A = "atk"
    C = "ccc"
    B = "break"


lst = ["A", 123, "B", 44, 2, "C"]

lst = [MyEnum[v].value if v in MyEnum.__members__ else v for v in lst]

print(lst)

Prints:

['atk', 123, 'break', 44, 2, 'ccc']
  • Related