Home > database >  Rearranging a Nested List Based on Index
Rearranging a Nested List Based on Index

Time:01-19

Let's say we have a nested list

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

I would like to create a new nested list where each list is organized based on the index

new_list = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

I would like to create a function that converts the nested_list into the new_list, but it's flexible where it can take in nested lists of different sizes/lengths.

Thanks

CodePudding user response:

nested_list = [[1, 2, 3], [1, 6, 2, 6], [0, 3, 7, 2, 6, 8, 2], [1, 3, 6, 2, 5]]

max_length = max([len(l) for l in nested_list])

new_list = [[l[i] for l in nested_list if i < len(l)] for i in range(max_length)]

print(new_list)

CodePudding user response:

You can achieve your result by:

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

new_list = list(map(list, zip(*nested_list)))
#[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Or you can use list comprehension as well:

new_list = [list(x) for x in zip(*nested_list)]
#[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

CodePudding user response:

From this code you can gain information of which nested list value the value is taken.

Code:

nested_list = [[1, 2, 3], [4, 5, 6, 7], [8, 10, 3, 1, 6, 2], [3, 4, 5, 2]]

max_length = max([len(l) for l in nested_list]) #Finding maximum length of nested lists

res=[]
for i in range(max_length):
    tmp=[]     #created a tmp list
    for l in nested_list:
        if i<len(l):
            tmp.append(l[i]) 
        else:
            tmp.append("-")  
    res.append(tmp)    

print(res)

Output:

[[1, 4, 8, 3], [2, 5, 10, 4], [3, 6, 3, 5], ['-', 7, 1, 2], ['-', '-', 6, '-'], ['-', '-', 2, '-']]

You can tell in result

1st nested list all values are obtained
2nd nested list all values are obtained
3rd nested list all values are obtained
4th nested list 3 values are obtained and you can also say that the values obtained is from 2nd,3rd,4th nested list.
5th nested list 1 value is obtained and it is from 3rd nested list. same as for 6th nested list.
  • Related