2

If ther is a list [[1,2,3],[4,5,6]] how do I convert it to [[1,4],[2,5],[3,6]] ?

def colu(j, data):
    return [data[i][j] for i in range(len(data))]

I understand that this code is from right to left but I don't know how to do it in the opposite way.

AA A
  • 29
  • 2

2 Answers2

2

an idiomatic way to transpose a nested list is this:

lst = [[1, 2, 3], [4, 5, 6]]

res = list(zip(*lst))
print(res)  # [(1, 4), (2, 5), (3, 6)]

if you instist on lists and not tuples:

res = [list(sublist) for sublist in zip(*lst)]
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
2

Use numpy NumPy aims to provide an array object that is up to 50x faster than traditional Python lists.

import numpy as np
numpy_lst = np.array(lst)
transposed = np.transpose(numpy_lst)
#if you convert back to list use
transposed_list = transposed.tolist()
Sivaram Rasathurai
  • 5,533
  • 3
  • 22
  • 45