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

后端 未结 16 1252
醉酒成梦
醉酒成梦 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:20

    Apart from the accepted answer, you can also initialise your rows in the following manner - matrix[i] = [0]*n

    Therefore, the following piece of code will work -

    m = int(input('number of rows, m = '))
    n = int(input('number of columns, n = '))
    matrix = []
    # initialize the number of rows
    for i in range(0,m):
        matrix += [0]
    # initialize the matrix
    for i in range (0,m):
        matrix[i] = [0]*n
    for i in range (0,m):
        for j in range (0,n):
            print ('entry in row: ',i+1,' column: ',j+1)
            matrix[i][j] = int(input())
    print (matrix)
    

提交回复
热议问题