我正在寻找一种优雅的方法来检查给定的索引是否在numpy数组中(例如用于网格上的BFS算法)。
以下代码可以实现我的要求:
import numpy as np
def isValid(np_shape: tuple, index: tuple):
if min(index) < 0:
return False
for ind,sh in zip(index,np_shape):
if ind >= sh:
return False
return True
arr = np.zeros((3,5))
print(isValid(arr.shape,(0,0))) # True
print(isValid(arr.shape,(2,4))) # True
print(isValid(arr.shape,(4,4))) # False
但我更喜欢内建的或比编写包含Python for循环的自己的函数更优雅的方法(天哪)。
def isValid(np_shape: tuple, index: tuple): return (0, 0) <= index <= np_shape
- DarrylGisValid
返回 False(与发布的问题相同)。 - DarrylG