gpt4 book ai didi

python - 矩阵外的函数输入

转载 作者:行者123 更新时间:2023-12-01 01:26:25 24 4
gpt4 key购买 nike

我正在编写一个带有参数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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com