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

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

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

20条回答
  •  Happy的楠姐
    2020-12-02 04:42

    Could it be that you're using a NumPy array? Python has the array module, but that does not support multi-dimensional arrays. Normal Python lists are single-dimensional too.

    However, if you have a simple two-dimensional list like this:

    A = [[1,2,3,4],
         [5,6,7,8]]
    

    then you can extract a column like this:

    def column(matrix, i):
        return [row[i] for row in matrix]
    

    Extracting the second column (index 1):

    >>> column(A, 1)
    [2, 6]
    

    Or alternatively, simply:

    >>> [row[1] for row in A]
    [2, 6]
    

提交回复
热议问题