Integrals Integrals - 18 days ago 5
Python Question

extracting sub array of array

Hi my question is in regards to the J.F. Sebastian code and discussion below.
I am trying to print a sub array of an array. The code is below and my update is on the bottom. (It gives error messages)creating a spiral array in python?

I want to create a sub array based on a chosen entry in this array. if we choose the 04 entry,

subarray[x][y] == 04
subarray[x][y] == TheSpiral[x-1:x+2,y-1:y+2]

print_matrix(TheSpiral)
print_matrix(subarray)


However I get an error message due to not properly defining subarray. I was expecting the print_matrix(subarray) to yield

06 01 02
05 04 03
16 15 14


which is why I used #TheSpiral[x-1:x+2,y-1:y+2]. Thanks for the help.

Answer

The issue is that the second slice doesn't do what you think it does

  • it's a syntax error with standard list and you should use [][], however ...
  • the second indices is not slicing the individual sub arrays, a slice returns the list of lists which the second slice would also operate on

You can fix it with a list comprehension:

>>> i, j = 3, 2
>>> subarray = [row[j-1:j+2] for row in TheSpiral[i-1:i+2]]
>>> print_matrix(subarray)
06 01 02
05 04 03
16 15 14

Alternatively you can use numpy (which maybe overkill!!!) and use your original syntax:

>>> import numpy as np
>>> subarray = np.array(TheSpiral)[i-1:i+2,j-1:j+2]
>>> print_matrix(subarray)
06 01 02
05 04 03
16 15 14