代码之家  ›  专栏  ›  技术社区  ›  P-Gn

np的行为。具有列表和元组参数的c_o

  •  7
  • P-Gn  · 技术社区  · 9 年前

    的输出 np.c_ 当其参数为列表或元组时不同。考虑以下三行的输出

    np.c_[[1,2]]
    np.c_[(1,2)]
    np.c_[(1,2),]
    

    np.c_

    有人能解释一下这种行为背后的原因吗?

    2 回复  |  直到 9 年前
        1
  •  6
  •   unutbu    9 年前

    有两个常见用例 np.c_ :

    • 可以接受1D数组序列,如:

      In [98]: np.c_[[1,2],[3,4]]
      Out[98]: 
      array([[1, 3],
             [2, 4]])
      
    • np.c_ 可以接受二维阵列序列,如:

      In [96]: np.c_[[[1,2],[3,4]], [[5,6],[7,8]]]
      Out[96]: 
      array([[1, 2, 5, 6],
             [3, 4, 7, 8]])
      

    np.c_ 可以传递1D数组类或2D数组类。 np.c_

    np.c_ 如果传递了一个元组,则参数将被视为一个单独的类数组序列。如果传递给它一个非元组(如列表),则该对象将被视为一个类似于的单个数组。

    因此 np.c_[[1,2], [3,4]] (相当于 np.c_[([1,2], [3,4])] ([1,2], [3,4]) 作为两个独立的1D阵列。

    In [99]: np.c_[[1,2], [3,4]]
    Out[99]: 
    array([[1, 3],
           [2, 4]])
    

    相反 np.c_[[[1,2], [3,4]]] [[1,2], [3,4]] 作为单个2D阵列。

    In [100]: np.c_[[[1,2], [3,4]]]
    Out[100]: 
    array([[1, 2],
           [3, 4]])
    

    因此,对于您发布的示例:

    np.c_[[1,2]] 对待 [1,2]

    In [101]: np.c_[[1,2]]
    Out[101]: 
    array([[1],
           [2]])
    

    np.c_[(1,2)] 对待 (1,2)

    In [102]: np.c_[(1,2)]
    Out[102]: array([[1, 2]])
    

    np.c_[(1,2),] (1,2), (相当于 ((1,2),) )作为一个类数组的序列,因此类数组被视为一列:

    In [103]: np.c_[(1,2),]
    Out[103]: 
    array([[1],
           [2]])
    

    注:也许比大多数软件包,NumPy有一个历史的 treating lists and tuples differently np.array .

        2
  •  2
  •   hpaulj    9 年前

    __getitem__

    In [442]: class Foo():
         ...:     def __getitem__(self,args):
         ...:         print(args)
         ...:        
    In [443]: Foo()['str']
    str
    In [444]: Foo()[[1,2]]
    [1, 2]
    In [445]: Foo()[[1,2],]
    ([1, 2],)
    In [446]: Foo()[(1,2)]
    (1, 2)
    In [447]: Foo()[(1,2),]
    ((1, 2),)
    

    np.c_ 是的一个实例 np.lib.index_tricks.AxisConcatenator __获取项目__

        # handle matrix builder syntax
        if isinstance(key, str):
            ....
            mymat = matrixlib.bmat(...)
            return mymat
    
        if not isinstance(key, tuple):
            key = (key,)
    
         ....
        for k, item in enumerate(key):
            ....
    

    np.bmat

    任何包含以下内容的变体 [1,2] 与相同 ([1,2],) (1,2) ([1,2],[3,4]) .

    numpy 索引还区分列表和元组(尽管有一些不一致)。

    In [455]: x=np.arange(24).reshape(2,3,4)
    In [456]: x[0,1]               # tuple - index for each dim
    Out[456]: array([4, 5, 6, 7])
    In [457]: x[(0,1)]             # same tuple
    Out[457]: array([4, 5, 6, 7])
    In [458]: x[[0,1]]             # list - index for one dim
    Out[458]: 
    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]]])
    In [459]: x[([0,1],)]          # same
         ....