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

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

    The itemgetter operator can help too, if you like map-reduce style python, rather than list comprehensions, for a little variety!

    # tested in 2.4
    from operator import itemgetter
    def column(matrix,i):
        f = itemgetter(i)
        return map(f,matrix)
    
    M = [range(x,x+5) for x in range(10)]
    assert column(M,1) == range(1,11)
    
    0 讨论(0)
  • 2020-12-02 04:44

    If you have an array like

    a = [[1, 2], [2, 3], [3, 4]]
    

    Then you extract the first column like that:

    [row[0] for row in a]
    

    So the result looks like this:

    [1, 2, 3]
    
    0 讨论(0)
提交回复
热议问题