How to break a list and turn it into an array in Python?

Asked

Viewed 4,081 times

2

In case, I want to turn a list of a column into a 3x3 matrix in numerical order:

lista =([[1],
     [2],
     [3],
     [4],
     [5],
     [6],
     [7],
     [8],
     [9]])

With the expected result:

([[7 8 9]
 [4 5 6]
 [1 2 3]])
  • Check the function reshape, but it needs an array, but to convert it there should not be difficult

1 answer

2

Using numpy:

import numpy as np
lista = np.arange(1, 10).reshape(9, 1)
print(lista)
'''
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])
'''

Now we can do:

lista = lista.reshape(3, 3)[::-1] # forma-lo em 3 linhas e 3 colunas, e inverter
print(lista)
'''
array([[7, 8, 9],
       [4, 5, 6],
       [1, 2, 3]])
'''

DEMONSTRATION

Browser other questions tagged

You are not signed in. Login or sign up in order to post.