我如何找到矩阵中是否可用的索引号? 像
将numpy导入为np
R= np.matrix ([1,2,34,4,5,5,6,9],
[1,2,34,4,5,5,6,9],
[1,2,34,4,5,5,6,9])
我要在这里搜索我的输入索引是否在“ R”中
Here my input index is C[4,4]
我想确定C [4,4]索引是否可用,然后他返回True,否则返回False 请帮我找到我的东西。
答案 0 :(得分:1)
您只需检查矩阵的尺寸即可。...*** Test Cases ***
Only upper limit
[Documentation] Loops over values from 0 to 9
:FOR ${index} IN RANGE 10
\ Log ${index}
答案 1 :(得分:0)
您的矩阵定义缺少[
.... ]
。
您可以使用Ask for forgiveness not permission方法,也可以测试给定的索引是否不超过矩阵的形状:
import numpy as np
R = np.matrix ([ # missing [
[1,2,34,4,5,5,6,9],
[1,2,34,4,5,5,6,9],
[1,2,34,4,5,5,6,9]
]) # missing ]
print( R.shape ) # (3,8)
def indexAvailable(M,a,b):
# ask forgiveness not permission by simply accessing it
# when testing for if its ok to access this
try:
p = M[a,b]
except:
return False
return True
print(99,22,indexAvailable(R,99,22))
print(9,2,indexAvailable(R,9,2))
print(2,2,indexAvailable(R,2,2))
输出:
99 22 False
9 2 False
2 2 True
或者您可以对照矩阵的形状检查所有给定的索引:
def indexOk(M,*kwargs):
"""Test if all arguments of kwargs must be 0 <= value < value in M.shape"""
try:
return len(kwargs) == len(M.shape) and all(
0 <= x < M.shape[i] for i,x in enumerate(kwargs))
except:
return False
print(indexOk(R,1,1)) # ok
print(indexOk(R,1,1,1)) # too many dims
print(indexOk(R,3,7)) # first too high
print(indexOk(R,2,8)) # last too high
print(indexOk(R,2,7)) # ok
输出:
True
False
False
False
True