Home > Software design >  Convert list of rows to list of columns Python
Convert list of rows to list of columns Python

Time:11-23

Python. How can I convert list of lists to list of columns lists according to number of indexes in lists. But every time I can have different matrix(dimension), different number of row/list and different number of numbers in list

For example from this list of lists:

 x = [
     [1, 0, 0, 0, 1, 0, 0],
     [0, 0, 2, 2, 0, 0, 0],
     [0, 1, 0, 0, 0, 2, 2]
 ]

To this list of column lists:

y = [[1,0,0],[0,0,1],[0,2,0],[0,2,0],[1,0,0],[0,0,2],[0,0,2]]

CodePudding user response:

You can use zip to do this. By unpacking x into its sublists and passing it into zip, you can get the format you want:

x = [
    [1, 0, 0, 0, 1, 0, 0],
    [0, 0, 2, 2, 0, 0, 0],
    [0, 1, 0, 0, 0, 2, 2]
]

y = list(zip(*x))
print(y)
>>> [(1, 0, 0), (0, 0, 1), (0, 2, 0), (0, 2, 0), (1, 0, 0), (0, 0, 2), (0, 0, 2)]

CodePudding user response:

With numpy:

x = numpy.fliplr(numpy.rot90(x, k=3))

rot90 rotates the array, fliplr flips the array, so it looks like a list of columns

with just python functions:

x = list(zip(*x))

It will output list of tuples. If you need list of lists:

x = list(map(list, zip(*x)))

zip basically converts columns to rows and returns them as tuples. It takes iterables, so by writing *x you pass each row as an iterable. And then with map and list the tuples are converted back to lists.

  • Related