Lists sorting in Python (transpose)
Asked Answered
F

1

7

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

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

And I want transpose them together in order to get the output like this:

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

As, you can see, I just converted "columns" to "rows".

The issue is a solution has to be independent of the lists length.

For example:

a = [1,1]
b = [2]
c = [3,3,3]
# output
f_out = [1,2,3]
g_out = [1,3]
n_out = [3]
Farrel answered 23/11, 2015 at 16:5 Comment(3)
You might want to look into itertools.zip_longest -- That's almost what you want, you'd just have to filter out the extra padding.Zest
@Zest Thank you! I think it can help me :)Farrel
For anyone else just staring at this question and wondering what the relationship between the input and output is, it's treating it almost like a transpose matrix. IOW, f, g, and h result from lining a, b, and c up horizontally and reading top to bottom.Sauncho
B
12

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 the lists, use a sentinel object instead of the default 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]]
Beverleybeverlie answered 23/11, 2015 at 16:16 Comment(2)
It is zip_longest for python3Minimal
@PadraicCunningham: Good catch -- fixedBeverleybeverlie

© 2022 - 2024 — McMap. All rights reserved.