有几种选择。下面假设您要迭代1d NumPy数组。
迭代 range
for j in range(theta.shape[0]): # or range(len(theta)) some_function(j, theta[j], theta)
请注意,这是可与一起使用的3种解决方案中的唯一一种
numba。这是值得注意的,因为在NumPy数组上进行显式迭代通常仅在与
numba预编译组合或其他方式结合时才有效。
迭代
enumerate
for idx, j in enumerate(theta): some_function(idx, j, theta)
3维解决方案中最有效的一维阵列。请参阅下面的基准测试。
迭代
np.ndenumerate
for idx, j in np.ndenumerate(theta): some_function(idx[0], j, theta)
请注意中的附加索引步骤
idx[0]。这是必要的,因为
shape1d
NumPy数组的索引(如)作为单例元组给出。对于一维数组,
np.ndenumerate效率不高;它的优势仅表现在多维数组上。
绩效基准
# Python 3.7, NumPy 1.14.3np.random.seed(0)arr = np.random.random(10**6)def enumerater(arr): for index, value in enumerate(arr): index, value passdef ranger(arr): for index in range(len(arr)): index, arr[index] passdef ndenumerater(arr): for index, value in np.ndenumerate(arr): index[0], value pass%timeit enumerater(arr) # 131 ms%timeit ranger(arr) # 171 ms%timeit ndenumerater(arr) # 579 ms


![如何使用索引和值迭代一维NumPy数组[重复] 如何使用索引和值迭代一维NumPy数组[重复]](http://www.mshxw.com/aiimages/31/574821.png)
