KateMac
KateMac

Reputation: 33

How do I flatten lists containing two strings and another list by one level?

I have an extensive list of lists where each contains two strings and another list with numbers:

lists = [
    ['A0A 4L0', 'ABBY', [38.065, 38.74, 61.987, 27.375, 105.675, 37.578]], 
    ['A0A 0A7', 'JOHN', [38.196, 39.222, 60.804, 24.139, 99.158, 31.609]],
]

I would like to flatten it into a list of lists containing just the strings and numbers, for example:

result = [
    ['A0A 4L0', 'ABBY', 38.065, 38.74, 61.987, 27.375, 105.675, 37.578], 
    ['A0A 0A7', 'JOHN', 38.196, 39.222, 60.804, 24.139, 99.158, 31.609],
]

I have tried using list comprehension and itertools.chain(), and neither one of these options flattened the list.

How can I do this?

Upvotes: 0

Views: 66

Answers (2)

DoctorHe
DoctorHe

Reputation: 81

your desired result is not fully flattened.

you can use a custom function to flatten the list.

def flatten(x: list) -> list:
    res = []
    for i in x:
        res.extend(flatten(i) if isinstance(i, list) else [i])
    return res

to fully flatten your list, you can do:

print(flatten(lists))

which will give you:

['A0A 4L0', 'ABBY', 38.065, 38.74, 61.987, 27.375, 105.675, 37.578, 'A0A 0A7', 'JOHN', 38.196, 39.222, 60.804, 24.139, 99.158, 31.609]

to get your desired result:

print([flatten(i) for i in lists])

which will give you:

[
    ['A0A 4L0', 'ABBY', 38.065, 38.74, 61.987, 27.375, 105.675, 37.578], 
    ['A0A 0A7', 'JOHN', 38.196, 39.222, 60.804, 24.139, 99.158, 31.609],
]

you can add tuple to conditions if you also want to flatten tuples:

import typing

def flatten(x: list) -> list:
    res = []
    for i in x:
        res.extend(flatten(i) if isinstance(i, typing.Union[list,tuple]) else [i])
    return res

Upvotes: 0

DPM
DPM

Reputation: 935

You can simply use:

result = [[el1, el2, *el3] for el1, el2, el3 in lists]

And the output will be:

[['A0A 4L0', 'ABBY', 38.065, 38.74, 61.987, 27.375, 105.675, 37.578],
 ['A0A 0A7', 'JOHN', 38.196, 39.222, 60.804, 24.139, 99.158, 31.609]]

Upvotes: 3

Related Questions