enumerate(sequence, [start = 0])
python内置的enumerate函数将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
- sequence: 序列、迭代器或者其他支持迭代的对象
- start: 下标起始位置
>>>seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
...print i, element
...
0 one
1 two
2 three
单独使用普通的for循环也可以做到同上一样的效果
>>>i = 0
>>> seq = ['one', 'two', 'three']
>>> for element in seq:
...print i, seq[i]
...i +=1
...
0 one
1 two
2 three
np.ndenumerate(arr)
在numpy中,np.ndenumerate()效果等同与enumerate,并且支持对多维数据的输出:
>>> Z = np.arange(9).reshape(3,3)
>>> for index, value in np.ndenumerate(Z):
...print(index, value)
...
(0, 0) 0
(0, 1) 1
(0, 2) 2
(1, 0) 3
(1, 1) 4
(1, 2) 5
(2, 0) 6
(2, 1) 7
(2, 2) 8
np.nindex(*shape)
用于求数列中元素的下标
An N-dimensional iterator object to index arrays.例:
Given the shape of an array, an ndindex instance iterates over the N-dimensional index of the array. At each iteration a tuple of indices is returned, the last dimension is iterated over first.
Parameters
*args
ints
The size of each dimension of the array.
>>> for index in np.ndindex(3, 2, 1):
...print(index)
(0, 0, 0)
(0, 1, 0)
(1, 0, 0)
(1, 1, 0)
(2, 0, 0)
(2, 1, 0)
【Python内置函数enumerate和Numpy中的np.ndenumerate()、np.nindex()】用np.nindex()可以达到和np.ndenumerate()一样的效果
>>> Z = np.arange(9).reshape(3,3)
>>> for index in np.ndindex(Z.shape):
print(index, Z[index])
...
(0, 0) 0
(0, 1) 1
(0, 2) 2
(1, 0) 3
(1, 1) 4
(1, 2) 5
(2, 0) 6
(2, 1) 7
(2, 2) 8