1

I have the next list

lst = [([0, 0, 1, 1], [0, 1, 0, 1], [0, 2, 1, 2], [1, 1, 0, 0]), ([0, 0, 1, 1], [0, 2, 1, 2], [0, 1, 0, 1], [1, 1, 0, 0])]

each set has 4 lists that contain 4 integers inside.

I need a matrix in numpy like this one, (for the first set, for example):

numpy_matrix = [ [0, 0, 1, 1] , [0, 1, 0, 1]
                [0, 2, 1, 2] , [1, 1, 0, 0] ]

notice that is a 2x2 matrix, and inside instead of saving integers is saving a list of those integers so I can do something like this:

print(numpy_array[0, 0][3]) # output: 1

I've tried this but didn't work:

np.matrix(lst[0]).reshape(2,-1)
# output:
# matrix([[0, 0, 1, 1, 0, 1, 0, 1],
#         [0, 2, 1, 2, 1, 1, 0, 0]])
3
  • 1
    arr = np.array(lst[0]).reshape(2, 2, 4)? Commented Oct 7, 2021 at 14:53
  • Yey, now It worked, could you elaborate why the 4 is nedeed there? Please, post it as an answer so I can give your reply as correct! thanks :) Commented Oct 7, 2021 at 15:00
  • Look at np.array(lst).shape. It's (2,4,4), right? What shape do you want? Your focus on lst[0] makes things a bit unclear, but I think you want (2,2,2,4) Commented Oct 7, 2021 at 15:38

1 Answer 1

1

If I understood correctly, you can do the following:

import numpy as np

lst = [([0, 0, 1, 1], [0, 1, 0, 1], [0, 2, 1, 2], [1, 1, 0, 0]),
       ([0, 0, 1, 1], [0, 2, 1, 2], [0, 1, 0, 1], [1, 1, 0, 0])]

arr = np.array(lst[0]).reshape(2, 2, 4)
print(arr)

Output

[[[0 0 1 1]
  [0 1 0 1]]

 [[0 2 1 2]
  [1 1 0 0]]]

The expression:

.reshape(2, 2, 4)

reshape the array to a 3-dimensional array where the length of the first dimension is 2, the second one is 2 and the last one is 4.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.