-1

here is my example

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

I would like to write method that will give me a list of ALL lists from enum. For that example it should return

[[1,3,5], [2,5,7], [33,49]]

I tried something like this:

listWithValues= [ z.value for z in MyClass]

But as you can guess it didnt work. Thanks for any helpful advices.

16
  • what does Enum look like?
    – KingMak
    Mar 20, 2017 at 19:40
  • Seems to work for me... Mar 20, 2017 at 19:40
  • 1
    What's wrong with your output, from the provided list comprehension you put in your question?
    – miradulo
    Mar 20, 2017 at 19:48
  • 1
    @Mateusz no, it isn't, because running your exact code is giving the output you say you want. So what output are you getting? Mar 20, 2017 at 19:48
  • 1
    @kindall in fact, it is documented that "Enumerations support iteration, in definition order". Mar 20, 2017 at 19:50

2 Answers 2

1

Here is a full example of what you want. This method will always return every list in the enumeration and ignore every other variable.

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

From the comments it sounds like you want a method on the class that will return a list of all the values. Try this:

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

and in use:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.