如果numpy数组索引不存在则设置为None
我在一个Python(2.7)类里面有一个函数,这个函数需要从一个二维的numpy数组中获取周围“单元格”的值。如果索引超出了范围,我希望这个值能被设置为None。
我在寻找一种方法来实现这个功能,但不想写8个try/catch语句,或者像我下面的代码那样使用多个if x else None的语句。虽然这两种方法都能工作,但感觉结构不太好,我在想一定有更简单的方法来做到这一点——我可能在思考这个问题时走入了误区。任何帮助都将非常感激。
# 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
1 个回答
6
这里有一个常用的小技巧:在你的棋盘周围加上一圈值为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
函数,这样就可以随意使用你喜欢的方式了。