Link_tester
Link_tester

Reputation: 1081

how to switch columns of a list with rows of another list in python

I have a list having some numpy arrays. I want to switch rows and columns of this list. My input list is:

array=[[np.array([[1.,2.]]), np.array([[5.,6.]]), np.array([[7.,8.]])],\
       [np.array([[10.,20.]]), np.array([[50.,60.]]), np.array([[70.,80.]])],\
       [np.array([[100.,200.]]), np.array([[500.,600.]]), np.array([[700.,800.]])]]

My array is a list which has three lists. Each list also has three numpy arrays. I want to rearrange these three lists. I want my first list to be the first array of first list, first array of second list and first array of third list. In the second list, I want to have second array of first list, second array of second list and second array of third list. For the third list again I want to have third arrays of first, second and third list. I mean I want to get:

[[np.array([[1.,2.]]), np.array([[10.,20.]]), np.array([[100.,200.]])],\
 [np.array([[5.,6.]]), np.array([[50.,60.]]), np.array([[500.,600.]])],\
 [np.array([[7.,8.]]), np.array([[70.,80.]]), np.array([[700.,800.]])]]

I tried:

switched=[]
for i in range (len(array)-1):
    for j in range (len (array[i])):
        switched.append ([array[i][j], array[i+1][j]])

But it does not give me what I want. I do appreciate if anyone help me to solve this issue.

Upvotes: 0

Views: 146

Answers (2)

Vincent Bénet
Vincent Bénet

Reputation: 1314

1: You can use zip build-in function of python to switch lines and columns.

array_tranformed = [list(column) for column in zip(*array)]

Upvotes: 1

TUI lover
TUI lover

Reputation: 552

switched = [[array[j][i] for j in range(len(array))] for i in range(len(array[0]))] should do the trick if your lists have the same size.

Upvotes: 2

Related Questions