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

前端 未结 20 2888
感情败类
感情败类 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:41

    let's say we have n X m matrix(n rows and m columns) say 5 rows and 4 columns

    matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20]]
    

    To extract the columns in python, we can use list comprehension like this

    [ [row[i] for row in matrix] for in range(4) ]
    

    You can replace 4 by whatever number of columns your matrix has. The result is

    [ [1,5,9,13,17],[2,10,14,18],[3,7,11,15,19],[4,8,12,16,20] ]

提交回复
热议问题