简体   繁体   中英

“Flatten” list containing lists of lists to list of lists

This question differs from Converting list of lists / nested lists to list of lists without nesting (this yields a very specific set of responses that do not address my situation) and also from the many "flatten list of lists to list" answers out there.

I want to take a list of lists, some of which are in turn lists of lists and "flatten" to a list of lists (not just a list!).

As a concrete example , I want to go from this:

my_list_of_lists = [[1, 2, 3], [[9, 10], [8, 9, 10], [3, 4, 6]], [11, 12, 13]]

to this

target_list_of_lists = [[1, 2, 3], [9, 10], [8, 9, 10], [3, 4, 6], [11, 12, 13]]

(In a visual sense, I want to turn all [[ and ]] inside the outer list into [ and ] respectively.)

Here's one way to do it:

def flatten(lst, dh=None):
    # Added so user does not need to pass output list
    if (dh is None):  
        dh = []
    for elem in lst:
        # Will not try to iterate through empty lists
        if elem and (isinstance(elem[0], list)):  
            flatten(elem, dh)
        else:
            dh.append(elem)
    return dh

my_list_of_lists = [[1, 2, 3], [[9, 10], [8, 9, 10], [3, 4, 6]], [11, 12, 13]]
target_list_of_lists = flatten(my_list_of_lists)
print(target_list_of_lists)

Output:

[[1, 2, 3], [9, 10], [8, 9, 10], [3, 4, 6], [11, 12, 13]]

This will work for lists of any length and any depth.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM