几行NumPy的代码就把别人打击了

标签:Python

起因是对方问怎么弄2维数组(其实是问Matlab的),结果不小心就变成show代码了…
>>> from numpy import *
>>> a = arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.shape = 2, 5
>>> a
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
嗯,3维:
>>> a = arange(32)
>>> a.shape = 2, 4, 4
>>> a
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11],
        [12, 13, 14, 15]],

       [[16, 17, 18, 19],
        [20, 21, 22, 23],
        [24, 25, 26, 27],
        [28, 29, 30, 31]]])
5维:
>>> a.shape = [2] * 5
>>> a
array([[[[[ 0,  1],
          [ 2,  3]],

         [[ 4,  5],
          [ 6,  7]]],


        [[[ 8,  9],
          [10, 11]],

         [[12, 13],
          [14, 15]]]],



       [[[[16, 17],
          [18, 19]],

         [[20, 21],
          [22, 23]]],


        [[[24, 25],
          [26, 27]],

         [[28, 29],
          [30, 31]]]]])
接着玩矩阵:
>>> a = mat('1 2 3; 4 5 6')
>>> a
matrix([[1, 2, 3],
        [4, 5, 6]])
>>> a.T
matrix([[1, 4],
        [2, 5],
        [3, 6]])
>>> a.I
matrix([[-0.94444444,  0.44444444],
        [-0.11111111,  0.11111111],
        [ 0.72222222, -0.22222222]])
>>> a * a.I
matrix([[  1.00000000e+00,   2.22044605e-16],
        [  0.00000000e+00,   1.00000000e+00]])
嗯,于是他睡觉去了…

我想这点片段已足以让其他语言的簇拥者对Python和NumPy动心了,所以更多的例子就不贴了,看片去。

0条评论 你不来一发么↓

    想说点什么呢?