How to create list of lists from sublists with varying length

Viewed 95

I am a beginner in python and I have this problem that I am hoping that someone could help me with.

first, I have a list of sublists with varying length

input:

temp_list=[[87.33372], [86.30815, 300.0], [96.31665, 300.0]]

I am trying to create a new list of lists, where the sublist consists of items of the same index from each list sublist, I hope this does not sound too convoluted.

maybe this will make it a bit more clear

desired output:

[[87.33372, 86.30815, 96.31665],[300.0, 300.0]]

I have thought of this formula but I'm not sure on how to implement it

x=0
new_list = [sublist[x][i],sublist[x+1][i]...]
3 Answers

You can use itertools.zip_longest with unpacking that helps you extract columns through the full length of sublists:

from itertools import zip_longest

temp_list = [[87.33372], [86.30815, 300.0], [96.31665, 300.0]]

result = [list(filter(lambda x: x is not None, x)) for x in zip_longest(*temp_list)]
# [[87.33372, 86.30815, 96.31665], [300.0, 300.0]]

I would recommend the same answer as Austin and i suggest its the cleanest however as a more verbose alternative which should easily illustrate whats happening in the code you could use the following.

temp_list = [[87.33372], [86.30815, 300.0], [96.31665, 300.0]]
new_list = []

#loop over each list
for items in temp_list:
    #for each item in the sublist get its index and value.
    for i, v in enumerate(items):
        #If the index is greater than the length of the new list add a new sublist
        if i >= len(new_list):
            new_list.append([])
        #Add the value at the index (column) position
        new_list[i].append(v)

print(new_list)

OUTPUT

[[87.33372, 86.30815, 96.31665], [300.0, 300.0]]

You already have one loop you would just need a second
This isn't the cleaned code in the world but it will do, you first calculate the max length which is basically the number of lists that the returned_list would have , create a return list ( a list of empty lists ) , then append each item when needed

temp_list=[[87.33372], [86.30815, 300.0], [96.31665, 300.0]]
max_length = max([len(i) for i in temp_list])
returned_list = [[] for i in range(max_length)]
for item in temp_list:
    for i in range(max_length):
        try:
            returned_list[i].append(item[i])
        except IndexError as ie:
            pass
Related