python matrix transpose

We usually encounter a problem, and want to map the elements in several different lists one by one, and then assign them to their respective lists, for example:

  We want to achieve from [[1, 2, 3], [1, 2, 3], [1, 2, 3]] to [[1, 1, 1], [2, 2, 2], [3, 3, 3]]

In fact, it is not difficult to understand and realize this from a mathematical point of view. In fact, it is the problem of transposing the matrix . Then the key question is, how can we realize the transposition of the matrix. Today, I will tell you a good method, using the numpy library of python in 2 steps It can be done easily~

  Key commands:

import numpy as np

np.transpose([list])     #Matrix transpose 
np.transpose([list]).tolist() #Matrix     to list

  demo:

>>> import numpy as np
>>> np.transpose([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])
>>> np.transpose([[1, 2, 3], [1, 2, 3], [1, 2, 3]]).tolist()
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]

Hope it helps you~

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324966372&siteId=291194637