Python Forum

Full Version: help with flatten nested list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to flatten my nested list

Input:

list1=[[[0],[1400,100]],[[0],[1200,100]],[[100],[800,400]]]

Expected output:

flattened1=[[0,1400,100],[0,1200,100],[100,800,400]]

Any ideas on how to achieve the outcome aboove?

Many thanks
What have you tried? We're not going to write your code for you, but we would be happy to help you fix your code when you run into problems. When you do run into problems, be sure to post your code in Python tags, and clearly explain the problem you are having, including the full text of any errors.
you can have a look at the code below. It does the thing that I need, but I was wondering if there is anohter way to acheive the same outcome with fewer lines of codes or maybe less iteration through using python modules. any ideas on how to acheive the same output?

list1=[[[0],[1400,100]],[[0],[1200,100]],[[100],[800,400]]]




flattened_list = []
for x in list1:
    flattened_list.append([])
    for y in x:
        if type(y) is list:
            for z in y:
                flattened_list[-1].append(z)
        else:
            flattened_list[0].append(y)


print (flattened_list)
Just a nitpicking, but there is subtle difference between flat list and list with flattened elements in it (a.k.a list of lists; two-dimensional list; matrix).

>>> list_of_lists = [[0, 1400, 100], [0, 1200, 100], [100, 800, 400]] 
>>> flat_list = [0, 1400, 100, 0, 1200, 100, 100, 800, 400]
@perfringo

Please have a look at the post above. I know the difference between flattened list and nested list. but in the example above as you can see i am aiming for flattened nested list which is a combination of nested list flatten at specific index. Feel free to post another code that get me the result I am seeking.
Specific conditions are unknown to me therefore I assume, that code must deliver result only in this particular case. This is the shortest I am able to write:

>>> list1=[[[0],[1400,100]],[[0],[1200,100]],[[100],[800,400]]] 
>>> [sum(row, []) for row in list1]
[[0, 1400, 100], [0, 1200, 100], [100, 800, 400]]
In slightly longer form:

>>> list1=[[[0],[1400,100]],[[0],[1200,100]],[[100],[800,400]]] 
>>> [[el for lst in row for el in lst] for row in list1]
[[0, 1400, 100], [0, 1200, 100], [100, 800, 400]]
Note that each sub-list follows the same pattern, and there are always two sub-sub-lists.

[a + b for a, b in list1]