Python - Transpose List of lists of various lengths - 3.3 the 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, Type Type does not seem to be accepted.

Is there a simple method in Python 3 to get the same result.

+4
source share
3 answers

You can use itertools.zip_longestin Python 3:

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

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

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 ability to do anything you want in the absence of 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]]

, @gboffi, , :

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

Source: https://habr.com/ru/post/1525064/


All Articles