简体   繁体   English

如何查找输入索引在 Matrix 中可用或在 python 中不可用

[英]How to find input index is available in Matrix or not in python

How i can find the index number is available in matrix or not?我如何才能找到索引号是否在矩阵中可用? Like喜欢

import numpy as np将 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])

Here i want to search my input index is available or not in "R"在这里我想在“R”中搜索我的输入索引是否可用

Here my input index is C[4,4]

I want to find if C[4,4] index is available then he returns True otherwise False Please help me how i can find.我想找到 C[4,4] 索引是否可用,然后他返回 True 否则返回 False 请帮助我如何找到。

您可以检查矩阵的尺寸.... np.matrix.shape

Your matrix definition lacks surrounding [ .... ] .您的矩阵定义缺少围绕[ .... ]


You can either use the Ask for forgiveness not permission approach or test if your given indexes do not exceed the shape of the matrix:您可以使用请求宽恕而不是许可方法或测试您给定的索引是否不超过矩阵的形状:

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))

Output:输出:

99 22 False
9 2 False
2 2 True

Or you can check all your given indexes against the shape of your matrix:或者您可以根据矩阵的形状检查所有给定的索引:

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

Output:输出:

True
False
False
False
True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM