有几种选择。下面假设您正在迭代一维 NumPy 数组。
for j in range(theta.shape[0]): # or range(len(theta))
some_function(j, theta[j], theta)
请注意,这是可与numba 一起使用的 3 个解决方案中的 the only。这是值得注意的,因为显式迭代 NumPy 数组通常只有在与 numba 或其他预编译方式结合使用时才有效。
for idx, j in enumerate(theta):
some_function(idx, j, theta)
一维数组的 3 种解决方案中最有效的一种。请参阅下面的基准测试。
for idx, j in np.ndenumerate(theta):
some_function(idx[0], j, theta)
注意idx[0] 中的附加索引步骤。这是必要的,因为一维 NumPy 数组的索引(如 shape)是作为单例元组给出的。对于一维数组,np.ndenumerate 效率低下;它的好处只体现在多维数组上。
性能基准测试
# Python 3.7, NumPy 1.14.3
np.random.seed(0)
arr = np.random.random(10**6)
def enumerater(arr):
for index, value in enumerate(arr):
index, value
pass
def ranger(arr):
for index in range(len(arr)):
index, arr[index]
pass
def 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