Solution
from itertools import izip_longest # in Python 3 zip_longest
list([x for x in y if x is not None] for y in izip_longest(*A))
result:
[[186, 12, 122, 166, 133],
[192, 193, 188, 44],
[133, 154, 199, 23],
[56],
[78],
[96],
[100]]
Explanation
izip_longest gives you an iterator:
>>> from itertools import izip_longest
>>> izip_longest([1, 2, 3], [4, 5])
<itertools.izip_longest at 0x103331890>
Convert it into a list to see what it does:
>>> list(izip_longest([1, 2, 3], [4, 5]))
[(1, 4), (2, 5), (3, None)]
It takes one element from each list and puts them pairwise into a tuple. Furthermore, it fills missing values with None ( or another value you supply).
The * allows to give a function an unspecified number of arguments. For example, we can put our two lists inside another list and use * and it still works the same:
>>> list(izip_longest(*[[1, 2, 3], [4, 5]]))
[(1, 4), (2, 5), (3, None)]
This is not limited to two arguments. An example with three.
Single arguments:
>>> list(izip_longest([1, 2, 3], [4, 5], [6]))
[(1, 4, 6), (2, 5, None), (3, None, None)]
All arguments in one list with *:
>>> list(izip_longest(*[[1, 2, 3], [4, 5], [6]]))
[(1, 4, 6), (2, 5, None), (3, None, None)]
You don't want the None values. Filter them out with a list comprehension:
>>> [x for x in y if x is not None]
For your A, you get this:
>>> list(izip_longest(*A))
[(186, 12, 122, 166, 133),
(192, None, 193, 188, 44),
(133, None, 154, 199, 23),
(None, None, None, None, 56),
(None, None, None, None, 78),
(None, None, None, None, 96),
(None, None, None, None, 100)]
Now, y runs through all entries in this list such as (186, 12, 122, 166, 133). While x runs through each individual number in y such as 186. The outer [] creates a list. So instead of the tuple (186, 12, 122, 166, 133)
we get a list [186, 12, 122, 166, 133]. Finally, the if x is not None filters out the None values.