Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
枚举中的Python列表_Python_List_Enums - Fatal编程技术网

枚举中的Python列表

枚举中的Python列表,python,list,enums,Python,List,Enums,这是我的例子 class MyClass(Enum): x=[1,3,5] y=[2,5,7] w=[33,49] 我想写一个方法,它会给我一个所有列表的列表。例如,它应该返回 [[1,3,5], [2,5,7], [33,49]] 我试过这样的方法: listWithValues= [ z.value for z in MyClass] 但是你可以猜到,它不起作用。感谢您提供的有用建议。从评论中可以看出,您似乎希望在类上找到一个方法,该方法将返回所有值的列表。试试

这是我的例子

class MyClass(Enum):
    x=[1,3,5]
    y=[2,5,7]
    w=[33,49]
我想写一个方法,它会给我一个所有列表的列表。例如,它应该返回

[[1,3,5], [2,5,7], [33,49]]
我试过这样的方法:

listWithValues= [ z.value for z in MyClass]

但是你可以猜到,它不起作用。感谢您提供的有用建议。

从评论中可以看出,您似乎希望在类上找到一个方法,该方法将返回所有值的列表。试试这个:

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

>>> MyClass.all_values()
[[1, 3, 5], [2, 5, 7], [33, 49]]

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

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())

Enum看起来像什么?对我来说似乎很有用…从您在问题中提供的列表理解来看,您的输出有什么问题?@Mateusz不,不是,因为运行您的精确代码就是给出您想要的输出。那么你得到了什么样的输出?@kindall事实上,它是“枚举支持迭代,按照定义顺序”。