【问题标题】:Python list of lists from enum来自枚举的 Python 列表
【发布时间】:2017-03-20 19:38:04
【问题描述】:

这是我的例子

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]

但是你可以猜到它没有用。感谢您提供任何有用的建议。

【问题讨论】:

  • 枚举是什么样子的?
  • 似乎对我有用...
  • 根据您在问题中提供的列表理解,您的输出有什么错误
  • @Mateusz 不,不是,因为运行 您的确切代码 会给出您想要的输出。那么你得到了什么输出?
  • @kindall 其实就是documented,“枚举支持迭代,按定义顺序”。

标签: python list enums


【解决方案1】:

从 cmets 看来,您需要一个类上的方法,该方法将返回所有值的列表。试试这个:

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

并在使用中:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-28
      • 2018-03-31
      • 1970-01-01
      • 2022-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多