索引,切片和迭代

一维 数组可以被索引、切片和迭代,就像 列表 和其它Python序列。

>>> a = arange(10)**3
>>> a
array([  0,   1,   8,  27,  64, 125, 216, 343, 512, 729])
>>> a[2]
8
>>> a[2:5]
array([ 8, 27, 64])
>>> a[:6:2] = -1000    # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000
>>> a
array([-1000,     1, -1000,    27, -1000,   125,   216,   343,   512,   729])
>>> a[ : :-1]                                 # reversed a
array([  729,   512,   343,   216,   125, -1000,    27, -1000,     1, -1000])
>>> for i in a:
...         print i**(1/3.),
...
nan 1.0 nan 3.0 nan 5.0 6.0 7.0 8.0 9.0
>>> a = arange(10)**3
>>> a
array([  0,   1,   8,  27,  64, 125, 216, 343, 512, 729])
>>> a[2]
8
>>> a[2:5]
array([ 8, 27, 64])
>>> a[:6:2] = -1000    # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000
>>> a
array([-1000,     1, -1000,    27, -1000,   125,   216,   343,   512,   729])
>>> a[ : :-1]                                 # reversed a
array([  729,   512,   343,   216,   125, -1000,    27, -1000,     1, -1000])
>>> for i in a:
...         print i**(1/3.),
...
nan 1.0 nan 3.0 nan 5.0 6.0 7.0 8.0 9.0


>>> a = random.random((2,3))
 >>> a
 array([[ 0.36639821,  0.44035901,  0.74424943],
        [ 0.74506957,  0.9945401 ,  0.59842882]])
 >>> a.sum()
 3.8890451481386368
 >>> a.min()
 0.36639821076181855
 >>> a.max()
 0.99454010014688865
 >>> b = arange(12).reshape(3,4)
 >>> b
 array([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])
 >>> b.sum()
 66
 >>> b.sum(0)
 array([12, 15, 18, 21])
 >>> b.sum(1)
 array([ 6, 22, 38])
 >>> b.min(0)
 array([0, 1, 2, 3])
 >>> b.min(1)
 array([0, 4, 8])
 >>> B=array([1,4,9])
 >>> sqrt(B)
 array([ 1.,  2.,  3.])
 >>> C=array([9,1,4])
 >>> c
 array([ 1.        ,  2.57079633,  4.14159265])
 >>> C
 array([9, 1, 4])
 >>> add(B,C)
 array([10,  5, 13])
 >>> C
 array([9, 1, 4])
 >>> B
 array([1, 4, 9])
 >>> C=array([9,4,1])
 >>> add(B,C)
 array([10,  8, 10])
 >>> a = arange(10)
 >>> a
 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
 >>> b=a**2
 >>> b
 array([ 0,  1,  4,  9, 16, 25, 36, 49, 64, 81])
 >>> c=b**3
 >>> c
 array([     0,      1,     64,    729,   4096,  15625,  46656, 117649,
        262144, 531441])
 >>> c=a**3
 >>> c
 array([  0,   1,   8,  27,  64, 125, 216, 343, 512, 729])
 >>> c[2]
 8
 >>> c[0]
 0
 >>> c[7]
 343
 >>> c[2:3]
 array([8])
 >>> c[0:3]
 array([0, 1, 8])
 >>> c
 array([  0,   1,   8,  27,  64, 125, 216, 343, 512, 729])
 >>> c[:6:2]=-1000
 >>> c
 array([-1000,     1, -1000,    27, -1000,   125,   216,   343,   512,   729])
 >>> c[::-1]
 array([  729,   512,   343,   216,   125, -1000,    27, -1000,     1, -1000])
 >>> c
 array([-1000,     1, -1000,    27, -1000,   125,   216,   343,   512,   729])
 >>> c
 array([-1000,     1, -1000,    27, -1000,   125,   216,   343,   512,   729])
 >>>