如何用索引和值迭代一个numpy数组

时间:2021-12-12 12:32:40

For python list, I could use iteritems() to loop through index and value at the same time. But I cannot find such functionality for numpy array. I have to manually track idx like this:

对于python列表,我可以使用iteritems()来同时遍历索引和值。但是我找不到numpy数组的这种功能。我必须像这样手动跟踪idx:

idx = 0 
for j in theta:
   some_function(idx,j,theta)
   idx += 1

Did I miss anything? Thank you.

我错过什么了吗?谢谢你!

1 个解决方案

#1


2  

There are 2 ways you can handle this for numpy arrays:

有两种方法可以处理numpy数组:

  1. Iterate a dimension of your numpy array.
  2. 迭代numpy数组的一个维度。

For example:

例如:

for j in range(theta.shape[0]):  # or range(len(theta))
   some_function(j, theta[j], theta)
  1. Use enumerate.
  2. 使用枚举。

For example:

例如:

for idx, j in enumerate(theta):
   some_function(idx, j, theta)

#1


2  

There are 2 ways you can handle this for numpy arrays:

有两种方法可以处理numpy数组:

  1. Iterate a dimension of your numpy array.
  2. 迭代numpy数组的一个维度。

For example:

例如:

for j in range(theta.shape[0]):  # or range(len(theta))
   some_function(j, theta[j], theta)
  1. Use enumerate.
  2. 使用枚举。

For example:

例如:

for idx, j in enumerate(theta):
   some_function(idx, j, theta)