locke14
locke14

Reputation: 1383

Python one-liner to get a combined list of all values of a list of Enum classes

I have 2 Enum classes defined as below:

class Enum1(Enum):
    V1 = 'v1'
    V2 = 'v2'

class Enum2(Enum):
   V1 = 'v1'
   V2 = 'v2'

I want a combine list of all the values in both Enum1 and Enum2. I currently do it this way:

enumList([Enum1, Enum2])

def enumList(Enums):
    l = []
    for E in Enums:
        l += list(map(lambda e: e, E))
    return  l

Running this, I get:

[<Enum1.V1: 'v1'>, <Enum1.V2: 'v2'>, <Enum2.V1: 'v1'>, <Enum2.V2: 'v2'>]

Is there a one-liner enumList implementation that achieves the same?

My attempt:

def enumList(Enums):
    return sum([list(map(lambda e: e, E)) for E in Enums], [])

Upvotes: 2

Views: 478

Answers (3)

Sebastian Loehner
Sebastian Loehner

Reputation: 1322

from itertools import chain
combined = list(chain(Enum1, Enum2)) # [<Enum1.V1: 'v1'>, <Enum1.V2: 'v2'>, <Enum2.V1: 'v1'>, <Enum2.V2: 'v2'>]

Upvotes: 3

khelwood
khelwood

Reputation: 59111

The use of map seems unnecessary.

You can use a list comprehension with a nested for:

combined_list = [e for et in [Enum1, Enum2] for e in et]

Upvotes: 3

Sayse
Sayse

Reputation: 43300

You can use chain

from itertools import chain
list(chain(*map(lambda e: e, [Enum1, Enum2])))

Upvotes: 1

Related Questions