python - 矩阵外的函数输入

标签 python arrays list numpy matrix

我正在编写一个带有参数de的函数。 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

来源:I want to exception handle 'list index out of range.'

关于python - 矩阵外的函数输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53304890/

相关文章:

python - 如何使用python计算3d-RGB阵列的均值和标准差?

python - 在 Python 中创建包含列表列表的字典

c++ - boost::python: 编译失败,因为复制构造函数是私有(private)的

javascript - 如何将对象添加到firestore对象数组的第一个索引

python - 在 Python 中将数组转换为 DataFrame

c - 循环跳过 C 中的第二个输入

python - 遍历列表返回负索引

.net - 获取 f# 中列表的最后一个元素

python - 如何从图中提取点?

python - 替换列表中每个项目中的未知第一个字符时键入错误