Check element exists in array

后端 未结 6 824
说谎
说谎 2021-01-30 08:23

In PHP there a function called isset() to check if something (like an array index) exists and has a value. How about Python?

I need to use this on arrays because I get \

6条回答
  •  再見小時候
    2021-01-30 08:55

    In Python you might be in for some surprises if you ask for forgiveness in this case.

    try-except is not the right paradigm here.

    If you accidentally get negative indices your in for a surprise.

    Better solution is to provide the test function yourself:

    def index_in_array(M, index):
        return index[0] >= 0 and index[1] >= 0 and index[0]< M.shape[0] and index[1] < M.shape[1]
    

提交回复
热议问题