通过枚举值重写列表中的数据

发布于 2025-02-13 13:23:48 字数 301 浏览 0 评论 0原文

假设我有一个看起来像这样的枚举:

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

一个看起来像这样的列表:

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

如何使数组中的AB和C因其枚举价值而改变并看起来像这样?

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

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']

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

递刀给你 2025-02-20 13:23:48

您可以尝试是否每个列表元素是枚举值(请参阅,例如,如何测试是否存在具有特定名称的枚举成员?),在这种情况下只需替换值:

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

在线尝试在这里

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.

风蛊 2025-02-20 13:23:48

尝试:

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)

打印:

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

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']
好倦 2025-02-20 13:23:48

您只需使用 for ... in 要迭代list,然后基于类型检查,您可以在该列表索引处分配enum值。

from enum import Enum

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

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

for x in list:
    elIndex = list.index(x)
    if((type(x) is str) and (x in [n.name for n in MyEnum])):
        list[elIndex] = MyEnum[x].value
    else:
        list[elIndex] = x

print(list)

You can simply achieve this by using for...in loop to iterate the list and then based on the type checking you can assign the enum value at that list index.

from enum import Enum

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

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

for x in list:
    elIndex = list.index(x)
    if((type(x) is str) and (x in [n.name for n in MyEnum])):
        list[elIndex] = MyEnum[x].value
    else:
        list[elIndex] = x

print(list)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文