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

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

    Creating matrix with prepopulated numbers can be done with list comprehension. It may be hard to read but it gets job done:

    rows = int(input('Number of rows: '))
    cols = int(input('Number of columns: '))
    matrix = [[i + cols * j for i in range(1, cols + 1)] for j in range(rows)]
    

    with 2 rows and 3 columns matrix will be [[1, 2, 3], [4, 5, 6]], with 3 rows and 2 columns matrix will be [[1, 2], [3, 4], [5, 6]] etc.

    0 讨论(0)
  • 2020-11-27 07:27

    The problem is on the initialization step.

    for i in range (0,m):
      matrix[i] = columns
    

    This code actually makes every row of your matrix refer to the same columns object. If any item in any column changes - every other column will change:

    >>> for i in range (0,m):
    ...     matrix[i] = columns
    ... 
    >>> matrix
    [[0, 0, 0], [0, 0, 0]]
    >>> matrix[1][1] = 2
    >>> matrix
    [[0, 2, 0], [0, 2, 0]]
    

    You can initialize your matrix in a nested loop, like this:

    matrix = []
    for i in range(0,m):
        matrix.append([])
        for j in range(0,n):
            matrix[i].append(0)
    

    or, in a one-liner by using list comprehension:

    matrix = [[0 for j in range(n)] for i in range(m)]
    

    or:

    matrix = [x[:] for x in [[0]*n]*m]
    

    See also:

    • How to initialize a two-dimensional array in Python?

    Hope that helps.

    0 讨论(0)
  • 2020-11-27 07:29
    a,b=[],[]
    n=int(input("Provide me size of squre matrix row==column : "))
    for i in range(n):
       for j in range(n):
          b.append(int(input()))
        a.append(b)
        print("Here your {} column {}".format(i+1,a))
        b=[]
    for m in range(n):
        print(a[m])
    

    works perfectly

    0 讨论(0)
  • 2020-11-27 07:31

    You can make any dimension of list

    list=[]
    n= int(input())
    for i in range(0,n) :
        #num = input()
        list.append(input().split())
    print(list)
    

    output:

    code in shown with output

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