List sorting in Python (transpose)

I have arbitrary lists, for example, here are three lists:

a = [1,1,1,1] b = [2,2,2,2] c = [3,3,3,3] 

And I want to transpose them together to get the output as follows:

 f_out = [1,2,3] g_out = [1,2,3] ... n_out = [1,2,3] 

As you can see, I just converted the β€œcolumns” to β€œrows”.

The problem is that the solution does not depend on the length of the lists.

For instance:

 a = [1,1] b = [2] c = [3,3,3] # output f_out = [1,2,3] g_out = [1,3] n_out = [3] 
+6
source share
1 answer

You can use zip_longest

 >>> from itertools import zip_longest >>> a = [1,1] >>> b = [2] >>> c = [3,3,3] >>> f,g,h=[[e for e in li if e is not None] for li in zip_longest(a,b,c)] >>> f [1, 2, 3] >>> g [1, 3] >>> h [3] 

If None is a potential valid value in lists, use the object parameter instead of the standard None :

 >>> b = [None] >>> sentinel = object() >>> [[e for e in li if e is not sentinel] for li in zip_longest(a,b,c, fillvalue=sentinel)] [[1, None, 3], [1, 3], [3]] 
+11
source

All Articles