我正在编写一个带有参数d
和e
的函数。 d
表示用户输入的矩阵,e
表示矩阵中的起始位置。我能够将 e
定义为矩阵 d
的位置:
mainIndex = e[0]
secondIndex = e[1]
position = d[row][column]
我遇到一个挑战,如果用户输入的位置在用户输入的矩阵之外,它将返回 False;例如,如果矩阵 d = [[3,2,1],[6,5,4],[9,8,7]]
且 e = [3,0 ]
,它应该返回 False
而不是引发 index out of range
错误。我如何实现这一目标?
最佳答案
您应该能够捕获错误,如下所示:
mainIndex = e[0]
secondIndex = e[1]
try:
position = d[row][column]
except IndexError:
return False
关于python - 矩阵外的函数输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53304890/