gpt4 book ai didi

python - 有没有一种优雅的方法来检查是否可以在 numpy 数组中请求索引?

转载 作者:行者123 更新时间:2023-12-05 01:49:11 26 4
gpt4 key购买 nike

我正在寻找一种优雅的方法来检查给定索引是否在 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):
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

关于python - 有没有一种优雅的方法来检查是否可以在 numpy 数组中请求索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74412630/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com