DarkDrassher34
DarkDrassher34

Reputation: 59

How to write a code for a flattening of nested lists more concisely

I have a collection of nested lists in a list.

Think about the data like this:

numberlist1 = [[[1,2]]]
numberlist2 = [[[1,2]]]

This works exactly how I want it to work. However, it looks messy, and I am sure there is a better way to do it. Can anyone help me format this code?

list(chain(*chain(*(chain.from_iterable([numberlist1, numberlist2])))))

Upvotes: 1

Views: 75

Answers (2)

pylang
pylang

Reputation: 44525

Using more_itertools.collapse shortens this:

Given

import more_itertools as mit


nlst1 = [[[1, 2]]]
nlst2 = [[[1, 3]]]

Code

list(mit.collapse(nlst1 + nlst2))
# [1, 2, 1, 3]

more_itertools is a third-party package. Install via > pip install more_itertools.

Upvotes: 1

Ry-
Ry-

Reputation: 224942

The usual way to write your original:

list(chain.from_iterable(chain.from_iterable(chain(numberlist1, numberlist2))))

Making a shorter alias:

flat = chain.from_iterable

list(flat(flat(chain(numberlist1, numberlist2))))

The list comprehension – works best if you can pick meaningful names:

[c for a in chain(numberlist1, numberlist2) for b in a for c in b]

f u n c t i o n a l

def repeat(count, f):
    def g(x):
        for i in range(count):
            x = f(x)
        return x
    return g


list(repeat(3, flat)((numberlist1, numberlist2)))

Upvotes: 2

Related Questions