2 回答

qq_遁去的一_1
TA贡献1725条经验 获得超7个赞
您应该能够按如下方式捕获错误:
mainIndex = e[0]
secondIndex = e[1]
try:
position = d[row][column]
except IndexError:
return False

料青山看我应如是
TA贡献1772条经验 获得超8个赞
try / except
您可以编写一个函数并捕获IndexError。我还建议您不要链接索引器,而是使用arr[row, column]语法。例如:
d = np.array([[3,2,1],[6,5,4],[9,8,7]])
def get_val(A, idx):
try:
return A[tuple(idx)]
except IndexError:
return False
e = [3, 0]
f = [0, 2]
get_val(d, e) # False
get_val(d, f) # 1
if / else
通过if/else构造可以实现另一种更明确的解决方案:
def get_val(A, idx):
if all(i < j for i, j in zip(idx, A.shape)):
return A[tuple(idx)]
return False
由于我们使用tuple(idx),这两种解决方案都适用于任意维度。
添加回答
举报
0/150
提交
取消