[英]How to check if the input is within the first column of the matrix
我创建了一个名为rix
的矩阵。
rix = [[1,2,3],[4,5,6][7,8,9]]
作为输入,我有变量put
,它是长度为2
的单个列表,代表矩阵的位置。 我正在努力的部分是,如何检查变量put代表第一列中的某个位置?
将您的功能设计为通用; 它应使用参数row_n
( 行号 ),该参数表示您要检查其边界的行。 检查row_n
在你的存在rix
的名单。 然后,你做的比较put
与原来的第二个元素( 即代表预期的行长度 ) row_n
在长度rix
列表。
根据你的情况,你应该如果比较put
的第二个元素是小于或等于rix
的row_n
长度,然后回到你的布尔值。
您可以使用len(rix)
评估行数,使用len(rix[0])
评估矩阵具有的列数
所以
if len(rix) <= put[0]:
return false
elif len(rix[0]) <= put[1]:
return false
else:
return true
您还必须考虑负面指数。
def in_first_col(put, list2D):
row_idx, col_idx = put
# return False if we can't get the row
try:
row = list2D[row_idx]
except IndexError:
return False
# return False if row is empty
# return False if col_idx does not refer to first element of row
return row and (col_idx == 0 or col_idx == -len(row))
演示:
>>> rix = [[1,2,3],[4,5,6],[7,8,9]]
>>> in_first_col([1,1], rix)
>>> False
>>> in_first_col([2,0], rix)
>>> True
>>> in_first_col([5,0], rix)
>>> False
>>> in_first_col([-2,-3], rix)
>>> True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.