Set to none if the numpy array index does not exist

I have a function inside the Python class (2.7) that should retrieve the values โ€‹โ€‹of the "cells" around it in a 2-dimensional numpy array. If the index is out of range, I would set it to No.

I'm struggling to find a way to do this without writing 8 try / catch statements or without using a few if else else commands, as in my code below. Although both of them will work, they do not seem very well structured, and I think there should be an easier way to do this - I probably caught thinking about it completely wrong. Any help would be greatly appreciated.

# This will return a dictionary with the values of the surrounding points
def get_next_values(self, column, row):
    if not (column < self.COLUMNS and row < self.ROWS):
        print "Invalid row/column."
        return False

    nextHorizIsIndex = True if column < self.COLUMNS - 2 else False
    nextVertIsIndex = True if row < self.ROWS - 2 else False

    n = self.board[column, row-1] if column > 0 else None
    ne = self.board[column+1, row-1] if nextHorizIsIndex else None
    e = self.board[column+1, row] if nextHorizIsIndex else None
    se = self.board[column+1, row+1] if nextHorizIsIndex and nextVertIsIndex else None
    s = self.board[column, row+1] if nextVertIsIndex else None
    sw = self.board[column-1, row+1] if nextVertIsIndex else None
    w = self.board[column-1, row] if row > 0 else None
    nw = self.board[column-1, row-1] if 0 not in [row, column] else None

    # debug
    print n, ne, e, se, s, sw, w, nw
+5
source share
1 answer

: , None. 3x3

nw, n, ne, w, _, e, sw, s, se = (self.board[column-1:column+2, row-1:row+2]).ravel()

,

import numpy as np

board = np.empty((10,10), dtype = 'object')
board[:,:] = None
board[1:9, 1:9] = np.arange(64).reshape(8,8)
print(board)
# [[None None None None None None None None None None]
#  [None 0 1 2 3 4 5 6 7 None]
#  [None 8 9 10 11 12 13 14 15 None]
#  [None 16 17 18 19 20 21 22 23 None]
#  [None 24 25 26 27 28 29 30 31 None]
#  [None 32 33 34 35 36 37 38 39 None]
#  [None 40 41 42 43 44 45 46 47 None]
#  [None 48 49 50 51 52 53 54 55 None]
#  [None 56 57 58 59 60 61 62 63 None]
#  [None None None None None None None None None None]]

column = 1
row = 1
nw, n, ne, w, _, e, sw, s, se = (board[column-1:column+2, row-1:row+2]).ravel()
print(nw, n, ne, w, _, e, sw, s, se)
# (None, None, None, None, 0, 1, None, 8, 9)

,

  • , , None, 1, 0.
  • , , , print(board) . , , board[row-1:row+2, column-1:column+2]. , print_board, , .
+5

All Articles