示例代码:
import numpy as np
a = np.zeros((5,5))
a[[0,1]] = 1 #(list of indices)
print('results with list based indexing\n', a)
a = np.zeros((5,5))
a[(0,1)] = 1 #(tuple of indices)
print('results with tuple based indexing\n',a)
结果:
results with list based indexing
[[ 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1.]
[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]]
results with tuple based indexing
[[ 0. 1. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]]
你可能已经注意到,用列表索引数组与使用相同索引的元组结果不同。 我正在使用Python3和Numpy版本1.13.3。
在使用列表和元组对numpy数组进行索引时,基本区别是什么?
a[0,1], :]
。这样更清晰地向人类表明,该列表选择了两个完整的行。 - hpaulj