0

I am trying to split a nested list into multiple lists and assign their name dynamically. Untill now, I tried the code below, but it only works when we have equal length sublists and we give them names manually.

sub_list = [[1,2,3],[4,5,5],   [2,63,6]]

l1, l2, l3 = map(list, zip(*sub_list))
print(l1)
print(l2)
print(l3)

# Output
[1, 4, 2]
[2, 5, 63]
[3, 5, 6]

The approach above will fail when we have unequal length sublists such as (sub_list = [[1,2,3],[4,5], [2]]) and it does not give lists dynamic names.

I know it can be done by for loop, but I am not able to make list_name using a loop.

Any help will help me to reach more closure to my work

Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42
Jayank
  • 81
  • 1
  • 11

4 Answers4

0

you could use zip_longest from itertools as follows:

sub_list = [[1,2,3],[4,5], [2]]
from itertools import zip_longest
l1, l2, l3 = map(list, zip_longest(*sub_list))
print(l1)
print(l2)
print(l3)

Output:  
# [1, 4, 2]
# [2, 5, None]
# [3, None, None]
SanV
  • 855
  • 8
  • 16
0

Answering the first question: If you don't want to give a manual name assing the map() to just one variable:

sub_list = [[1,2,3],[4,5,5],   [2,63,6]]

rotated = map(list, zip(*sub_list))

for r in rotated:
    print(r)

# Output
# [1, 4, 2]
# [2, 5, 63]
# [3, 5, 6]
Manuel
  • 534
  • 3
  • 9
0

Not completely sure what you want to accomplish, but I suggest you take a look at:

Faboor
  • 1,365
  • 2
  • 10
  • 23
0

The following code performs in both of your special cases:

  1. There are no errors if some input lists are shorter than others
  2. Names are procedurally/dynamically generated

    def rotate_list_matrix(rows):
        nrows = len(rows)
    
        col_counts = map(lambda lyst: len(lyst), rows)
        ncols = max(col_counts)
    
        for ci in range(0, ncols): # column index
            lyst = list()
            list_name = "l" + str(ci + 1)
            globals()[list_name] = lyst
            for ri in range(0, nrows):
                try:
                    lyst.append(rows[ri][ci])
                except:
                    break
        return
    
    
    list_mata = [[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]]
    
    list_matb = [[1, 2, 3],
                 [4, 5   ],
                 [7      ]]
    
    rotate_list_matrix(list_matb)
    
    print(l1)
    print(l2)
    print(l3)
    
Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42