0

I have list a = [[1,2,3],[4,5,6],[7,8,9]] and want to convert that into list b = [[1,4,7],[2,5,8],[3,6,9]]. Is it possible to do that?

i.e. take all the value in the first element spot and combine into a new list, same for 2nd, 3rd etc...

Assume the initial list has an unknown amount of elements and each element has unknown length, i.e. there could be 40 elements in a and each element contains 14 numbers. Thanks

David
  • 8,113
  • 2
  • 17
  • 36
broccoli
  • 25
  • 6

2 Answers2

2

There are a couple of ways to do it.

The first one is as follows:

print(list(map(list, zip(*a))))

another option is using numpy as follows:

print(np.array(a).T.tolist())

Another option is to use list comprehension as follows:

print([[row[i] for row in a] for i in range(len(a[0]))])

David
  • 8,113
  • 2
  • 17
  • 36
1

Using numpy you can try this

import numpy as np


a= [[1,2,3],[4,5,6],[7,8,9]]
ar = np.array(a)
a_transpose = at.T.tolist()
Manik Tharaka
  • 298
  • 3
  • 9