之前一直对a[][][]
和 a[, , ]
两种索引方式的区别不清楚,今天试验了一下。
根据三个维度分别是:
还是数字
,共2^3^ =8
种情况进行了实验。
1、a[:][:][:] 与 a[:, :, :](等价于a[:]), a[1][0][2] 与 a[1, 0, 2]
# -*- coding: utf-8 -*-
import numpy as np
a = np.arange(24).reshape([2,3,4])
print('a = ')
print(a)
b1 = a[:][:][:]
c1 = a[:, :, :]
print('b1 = ')
print(b1)
print('c1 = ')
print(c1)
b2 = a[1][0][2]
c2 = a[1, 0, 2]
print('b2 = ')
print(b2)
print('c2 = ')
print(c2)
结果
a =
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
b1 =
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
c1 =
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
b2 =
14
c2 =
14
可以看到两种方式没有区别
2、形如 a[0][:][:] 与 a[0, :, :]
# -*- coding: utf-8 -*-
import numpy as np
a = np.arange(24).reshape([2,3,4])
print('a = ')
print(a)
b1 = a[0][:][:]
c1 = a[0, :, :]
print('b1 = ')
print(b1)
print('c1 = ')
print(c1)
b2 = a[:][0][:]
c2 = a[:, 0, :]
print('b2 = ')
print(b2)
print('c2 = ')
print(c2)
b3 = a[:][:][0]
c3 = a[:, :, 0]
print('b3 = ')
print(b3)
print('c3 = ')
print(c3)
结果
a =
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
b1 =
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
c1 =
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
b2 =
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
c2 =
[[ 0 1 2 3]
[12 13 14 15]]
b3 =
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
c3 =
[[ 0 4 8]
[12 16 20]]
可以看到a[0][:][:] ,a[:][0][:] ,a[:][:][0]效果一样(都是a[0][:][:]的结果
),而另一种方式是不同的
3、形如 a[0][0][:] 与 a[0, 0, :]
# -*- coding: utf-8 -*-
import numpy as np
a = np.arange(24).reshape([2,3,4])
print('a = ')
print(a)
b1 = a[0][0][:]
c1 = a[0, 0, :]
print('b1 = ')
print(b1)
print('c1 = ')
print(c1)
b2 = a[0][:][0]
c2 = a[0, :, 0]
print('b2 = ')
print(b2)
print('c2 = ')
print(c2)
b3 = a[:][0][0]
c3 = a[:, 0, 0]
print('b3 = ')
print(b3)
print('c3 = ')
print(c3)
结果
a =
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
b1 =
[0 1 2 3]
c1 =
[0 1 2 3]
b2 =
[0 1 2 3]
c2 =
[0 4 8]
b3 =
[0 1 2 3]
c3 =
[ 0 12]
同第二条,a[0][0][:] ,a[:][0][0] ,a[0][:][0]效果一样(都是a[0][0][:]的结果
),而另一种方式是不同的
个人理解:a[][][]这种方式索引时会自动把
:
调整到最后,而a[, ,]这种方式会正确按照顺序去索引