Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top