Search code examples
python-3.xlistnested-listssublistreorderlist

Python 3: how to re-order sublists of nested list?


I have the following nested list, and the number of sublist in the list:

l1 = [[['a','c','d'],['e','f','g'],[['a','b'],'d','1']], [['2','3','4'],['3','4','4'],[['1','2'],'3','4']], [['q1','3e','2e'],['r4','tt','t5'],[['t4','g4'],'r4','45g']]]
nb_sub = 3

I want to re-order the sublists by 'index', so the 1st sublist of each sublist, then 2nd sublist of each sublist, etc. The ouput I want is:

output = [[['a','c','d'],['2','3','4'],['q1','3e','2e']], [['e','f','g'],['3','4','4'],['r4','tt','t5']], [[['a','b'],'d','1'],[['1','2'],'3','4'],[['t4','g4'],'r4','45g']]]

Solution

  • zip seems to be the perfect tool for the job:

    output = [x for x in zip(*l1)]