How to input matrix (2D list) in Python?

后端 未结 16 1282
醉酒成梦
醉酒成梦 2020-11-27 06:34

I tried to create this code to input an m by n matrix. I intended to input [[1,2,3],[4,5,6]] but the code yields [[4,5,6],[4,5,6]. Same things happ

16条回答
  •  感动是毒
    2020-11-27 07:12

    I used numpy library and it works fine for me. Its just a single line and easy to understand. The input needs to be in a single size separated by space and the reshape converts the list into shape you want. Here (2,2) resizes the list of 4 elements into 2*2 matrix. Be careful in giving equal number of elements in the input corresponding to the dimension of the matrix.

    import numpy as np
    a=np.array(list(map(int,input().strip().split(' ')))).reshape(2,2)
    
    print(a)
    

    Input

    array([[1, 2],
           [3, 4]])
    

    Output

提交回复
热议问题