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

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

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

list(map(None,*a))

In Python 3 None type is seemingly not accepted.

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

Answers


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)]

Output:

[[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)]

Output:

[[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],
    [4,5,6],
    [7,8,9,10,12,25]]

i = 0
result = []
do_stop = False
while not do_stop:
    result.append([])
    for block in grid:
        try:
            result[i].append(block[i])
        except:
            continue
    if len(result[i]) == 0:
        result.pop(i)
        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).