I'd like to share all the lists

Asked 1 years ago, Updated 1 years ago, 152 views

L = [[[1, 2, 3], [4, 5]], 6] If the element in the list is a list like this

[1, 2, 3, 4, 5, 6] I'm going to release all the elements of the list together.

The way I know it, the list is [[1,2], [3,4], 5] You can use it when it's double [[[1, 2, 3], [4, 5]], 6] cannot be used when it is triple.

Is there any other way?

L = [[[1, 2, 3], [4, 5]], 6]
L = [item for sublist in L for item in sublist]
print L

python list optimization flatten

2022-09-22 22:23

1 Answers

For double lists, define the function flatten() that flatten the list If the element in the list is usable (excluding strings), use extend.

Expanding this allows multiple lists to be implemented by writing recursive functions within the flatten() function.

def flatten(x):
    result = []
    for el in x:
        if hasattr(el, "__iter__") and not isinstance(el, basestring): 
            #In case of non-string-type usefulness - after recursive, extend
            result.extend(flatten(el)) #recursive call
        else:
            #If it's not ugly or if it's a string -
            result.append(el)
    return result

flatten(L)

To speed up here, write generator.

def flatten(l):
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
            for sub in flatten(el):
                yield sub
        else:
            yield el

However, there is no basestring in Python3 Please define basestring = (str, byte) directly at the beginning.


2022-09-22 22:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.