How to make matrices in Python?

前端 未结 6 1160
闹比i
闹比i 2020-12-31 20:23

I\'ve googled it and searched StackOverflow and YouTube.. I just can\'t get matrices in Python to click in my head. Can someone please help me? I\'m just trying to create a

6条回答
  •  伪装坚强ぢ
    2020-12-31 21:06

    The answer to your question depends on what your learning goals are. If you are trying to get matrices to "click" so you can use them later, I would suggest looking at a Numpy array instead of a list of lists. This will let you slice out rows and columns and subsets easily. Just try to get a column from a list of lists and you will be frustrated.

    Using a list of lists as a matrix...

    Let's take your list of lists for example:

    L = [list("ABCDE") for i in range(5)]
    

    It is easy to get sub-elements for any row:

    >>> L[1][0:3]
    ['A', 'B', 'C']
    

    Or an entire row:

    >>> L[1][:]
    ['A', 'B', 'C', 'D', 'E']
    

    But try to flip that around to get the same elements in column format, and it won't work...

    >>> L[0:3][1]
    ['A', 'B', 'C', 'D', 'E']
    
    >>> L[:][1]
    ['A', 'B', 'C', 'D', 'E']
    

    You would have to use something like list comprehension to get all the 1th elements....

    >>> [x[1] for x in L]
    ['B', 'B', 'B', 'B', 'B']
    

    Enter matrices

    If you use an array instead, you will get the slicing and indexing that you expect from MATLAB or R, (or most other languages, for that matter):

    >>> import numpy as np
    >>> Y = np.array(list("ABCDE"*5)).reshape(5,5)
    >>> print Y
    [['A' 'B' 'C' 'D' 'E']
     ['A' 'B' 'C' 'D' 'E']
     ['A' 'B' 'C' 'D' 'E']
     ['A' 'B' 'C' 'D' 'E']
     ['A' 'B' 'C' 'D' 'E']]
    >>> print Y.transpose()
    [['A' 'A' 'A' 'A' 'A']
     ['B' 'B' 'B' 'B' 'B']
     ['C' 'C' 'C' 'C' 'C']
     ['D' 'D' 'D' 'D' 'D']
     ['E' 'E' 'E' 'E' 'E']]
    

    Grab row 1 (as with lists):

    >>> Y[1,:]
    array(['A', 'B', 'C', 'D', 'E'], 
          dtype='|S1')
    

    Grab column 1 (new!):

    >>> Y[:,1]
    array(['B', 'B', 'B', 'B', 'B'], 
          dtype='|S1')
    

    So now to generate your printed matrix:

    for mycol in Y.transpose():
        print " ".join(mycol)
    
    
    A A A A A
    B B B B B
    C C C C C
    D D D D D
    E E E E E
    

提交回复
热议问题