How do you extract a column from a multi-dimensional array?

前端 未结 20 2842
感情败类
感情败类 2020-12-02 03:56

Does anybody know how to extract a column from a multi-dimensional array in Python?

20条回答
  •  一整个雨季
    2020-12-02 04:20

    Well a 'bit' late ...

    In case performance matters and your data is shaped rectangular, you might also store it in one dimension and access the columns by regular slicing e.g. ...

    A = [[1,2,3,4],[5,6,7,8]]     #< assume this 4x2-matrix
    B = reduce( operator.add, A ) #< get it one-dimensional
    
    def column1d( matrix, dimX, colIdx ):
      return matrix[colIdx::dimX]
    
    def row1d( matrix, dimX, rowIdx ):
      return matrix[rowIdx:rowIdx+dimX] 
    
    >>> column1d( B, 4, 1 )
    [2, 6]
    >>> row1d( B, 4, 1 )
    [2, 3, 4, 5]
    

    The neat thing is this is really fast. However, negative indexes don't work here! So you can't access the last column or row by index -1.

    If you need negative indexing you can tune the accessor-functions a bit, e.g.

    def column1d( matrix, dimX, colIdx ):
      return matrix[colIdx % dimX::dimX]
    
    def row1d( matrix, dimX, dimY, rowIdx ):
      rowIdx = (rowIdx % dimY) * dimX
      return matrix[rowIdx:rowIdx+dimX]
    

提交回复
热议问题