0

say I have the following array j:

[[1, 2, 3, 4, 5], 
 [7, 7, 7, 6, 4], 
 [1, 1, 2, 0, 0]]

how can I get the subarray of 2x2 so the subarray would be:

[[1, 2], 
 [7, 7],]

intuitively I assumed j[0:2][0:2] would do the trick but I get:

[[1, 2, 3, 4, 5], [7, 7, 7, 6, 4]]
4
  • 2
    For numpy: j[:2, :2] Commented May 26, 2022 at 19:41
  • @mkrieger1 my fault I read the question wrong - removed the tag Commented May 26, 2022 at 19:43
  • Duplicate of stackoverflow.com/questions/72025278/… Commented May 26, 2022 at 19:44
  • Your use of array, subarray and matrix suggest you are using numpy. But the examples are indistinguishable from a list of lists. Commented May 26, 2022 at 19:44

3 Answers 3

2

You need to explicitly say what you want from each row:

[r[0:2] for r in j[0:2]]
Sign up to request clarification or add additional context in comments.

Comments

2

in numpy you can do this:

import numpy as np 
j = np.array([[1, 2, 3, 4, 5], 
 [7, 7, 7, 6, 4], 
 [1, 1, 2, 0, 0]])

j[:2, :2]

output:

>>
[[1 2]
 [7 7]]

Comments

0

You could also do:

[j[i][:2] for i in range(2)]

[[1, 2], 
 [7, 7]]

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.