sch*_*jan 6 python numpy built-in
我正在寻找一种优雅的方法来检查给定索引是否位于 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
Run Code Online (Sandbox Code Playgroud)
但我更喜欢内置的或更优雅的东西,而不是编写自己的函数,包括 python for 循环(yikes)
你可以试试:
def isValid(np_shape: tuple, index: tuple):
index = np.array(index)
return (index >= 0).all() and (index < arr.shape).all()
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
Run Code Online (Sandbox Code Playgroud)