Fast matrix transposition in Python

前端 未结 3 1634
温柔的废话
温柔的废话 2020-12-06 14:38

Is there any fast method to make a transposition of a rectangular 2D matrix in Python (non-involving any library import).?

Say, if I have an array

         


        
相关标签:
3条回答
  • 2020-12-06 14:58
    >>> X = [1,2,3], [4,5,6]]
    >>> zip(*X)
    [(1,4), (2,5), (3,6)]
    >>> [list(tup) for tup in zip(*X)]
    [[1,4], [2,5], [3,6]]
    

    If the inner pairs absolutely need to be lists, go with the second.

    0 讨论(0)
  • 2020-12-06 15:04

    Simple: Y=zip(*X)

    >>> X=[[1,2,3], [4,5,6]]
    >>> Y=zip(*X)
    >>> Y
    [(1, 4), (2, 5), (3, 6)]
    

    EDIT: to answer questions in the comments about what does zip(*X) mean, here is an example from python manual:

    >>> range(3, 6)             # normal call with separate arguments
    [3, 4, 5]
    >>> args = [3, 6]
    >>> range(*args)            # call with arguments unpacked from a list
    [3, 4, 5]
    

    So, when X is [[1,2,3], [4,5,6]], zip(*X) is zip([1,2,3], [4,5,6])

    0 讨论(0)
  • 2020-12-06 15:09

    If you're working with matrices, you should almost certainly be using numpy. This will perform numerical operations easier and more efficiently than pure Python code.

    >>> x = [[1,2,3], [4,5,6]]
    >>> x = numpy.array(x)
    >>> x
    array([[1, 2, 3],
           [4, 5, 6]])
    >>> x.T
    array([[1, 4],
           [2, 5],
           [3, 6]])
    

    "non-involving any library import" is a silly, non-productive requirement.

    0 讨论(0)
提交回复
热议问题