-2

I have a list like this: A_list = [0, 5, 20, 0, 1, 8, 0, 14, 7, 5, 11, 0, 7, 0, 4, 0, 0, 0].

I want it to convert into 'matrix' form in python without using numpy.

A_matrix = [ [0, 0, 0, 5, 7, 0],
             [5, 1, 14, 11, 0, 0],
             [20, 8, 7, 0, 4, 0]
           ]
gapansi
  • 105
  • 2
  • 10

1 Answers1

1

You can use a list comprehension to stride through the array, where each inner list starts at a different offset

>>> [A_list[start::3] for start in range(3)]
[[0, 0, 0, 5, 7, 0], [5, 1, 14, 11, 0, 0], [20, 8, 7, 0, 4, 0]]

This is basically what you'd achieve with numpy.reshape

>>> np.array(A_list).reshape((-1,3)).T
array([[ 0,  0,  0,  5,  7,  0],
       [ 5,  1, 14, 11,  0,  0],
       [20,  8,  7,  0,  4,  0]])
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218