Python - Transpose List of Lists of various lengths - 3.3 easiest method


In Python 2 If I have a list containing lists of variable lengths then I can do the following:


In Python 3 None type is seemingly not accepted.

Is there, in Python 3, an as simple method for producing the same result.


You can use itertools.zip_longest in Python 3:

>>> from itertools import zip_longest
>>> list(zip_longest(*a))
[(1, 4, 7), (2, 6, 8), (3, None, 9)]

You can also use list comprehensions to do this, which I guess should work regardless of the Python version:

max_len = max(len(i) for i in a)
[[i[o] if len(i) > o else None for i in a] for o in range(max_len)]


[[1, 4, 7], [2, 6, 8], [3, None, 9]]

This gives you the flexibility to do whatever you want in case of missing values.

max_len = max(len(i) for i in a)
[[i[o] for i in a if len(i) > o] for o in range(max_len)]


[[1, 4, 7], [2, 6, 8], [3, 9]]

Alternately, as suggested by @gboffi, you can do the following to save more time:

l = [len(i) for i in a]
[[i[o] for ix, i in enumerate(a) if l[ix] > o] for o in range(max(l))]

grid = [[1],

i = 0
result = []
do_stop = False
while not do_stop:
    for block in grid:
    if len(result[i]) == 0:
        do_stop = True
    i = i + 1

print result

Need Your Help

Setting image DPI in relation to height/width C#

c# image

I'm writing an application to send some images to a third party, and the images must be 200x200 DPI. The image is a Bitmap and is sized at 500 width and 250 height.

find django/contrib/admin/templates

python django ubuntu django-templates

I have trouble to see django/contrib/admin/templates folder. It seems like it is hidden in /usr/lib/python2.7/dist-packages/ folder, ctrl+h wont help ( appearencely all django files are hidden).