来自enum的列表的Python列表

2024-09-29 23:32:07 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的例子

class MyClass(Enum):
    x=[1,3,5]
    y=[2,5,7]
    w=[33,49]

我想编写一个方法,它将给我一个枚举中所有列表的列表。对于这个例子,它应该返回

^{pr2}$

我试过这样的方法:

listWithValues= [ z.value for z in MyClass]

但你可以猜到它没用。谢谢你的建议。在


Tags: 方法in列表forvaluemyclassenum建议
2条回答

从注释来看,您似乎希望类上有一个方法,该方法将返回所有值的列表。试试这个:

    @classmethod
    def all_values(cls):
        return [m.value for m in cls]

使用中:

^{pr2}$

这里有一个完整的例子说明你想要什么。此方法将始终返回枚举中的每个列表,并忽略所有其他变量。在

import enum


class MyClass(enum.Enum):
    x = [1, 2, 3]
    y = [4, 5, 6]
    z = "I am not a list"
    w = ["But", "I", "Am"]

    @classmethod
    def get_lists(cls):
        """ Returns all the lists in the Enumeration"""
        new_list = []

        for potential_list in vars(cls).values():  # search for all of MyClass' attributes
            if (isinstance(potential_list, cls)  # filter out the garbage attributes
                    and isinstance(potential_list.value, list)  # only get the list attributes
                    and len(potential_list.value) != 0):  # only get the non-empty lists

                new_list.append(potential_list.value)

        return new_list


print(MyClass.get_lists())

相关问题 更多 >

    热门问题