How to make matrices in Python?

前端 未结 6 1209
闹比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:19

    Looping helps:

    for row in matrix:
        print ' '.join(row)
    

    or use nested str.join() calls:

    print '\n'.join([' '.join(row) for row in matrix])
    

    Demo:

    >>> matrix = [['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']]
    >>> for row in matrix:
    ...     print ' '.join(row)
    ... 
    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 '\n'.join([' '.join(row) for row in matrix])
    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
    

    If you wanted to show the rows and columns transposed, transpose the matrix by using the zip() function; if you pass each row as a separate argument to the function, zip() recombines these value by value as tuples of columns instead. The *args syntax lets you apply a whole sequence of rows as separate arguments:

    >>> for cols in zip(*matrix):  # transposed
    ...     print ' '.join(cols)
    ... 
    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
    

提交回复
热议问题