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

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

    m,n=map(int,input().split()) # m - number of rows; n - number of columns;

    matrix = [[int(j) for j in input().split()[:n]] for i in range(m)]

    for i in matrix:print(i)

    0 讨论(0)
  • 2020-11-27 07:04
    no_of_rows = 3  # For n by n, and even works for n by m but just give no of rows
    matrix = [[int(j) for j in input().split()] for i in range(n)]
    print(matrix)
    
    0 讨论(0)
  • 2020-11-27 07:06

    This code takes number of row and column from user then takes elements and displays as a matrix.

    m = int(input('number of rows, m : '))
    n = int(input('number of columns, n : '))
    a=[]
    for i in range(1,m+1):
      b = []
      print("{0} Row".format(i))
      for j in range(1,n+1):
        b.append(int(input("{0} Column: " .format(j))))
      a.append(b)
    print(a)
    
    0 讨论(0)
  • 2020-11-27 07:07
    a = []
    b = []
    
    m=input("enter no of rows: ")
    n=input("enter no of coloumns: ")
    
    for i in range(n):
         a = []
         for j in range(m):
             a.append(input())
         b.append(a)
    

    Input : 1 2 3 4 5 6 7 8 9

    Output : [ ['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'] ]

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

    If the input is formatted like this,

    1 2 3
    4 5 6
    7 8 9
    

    a one liner can be used

    mat = [list(map(int,input().split())) for i in range(row)]
    
    0 讨论(0)
  • 2020-11-27 07:09
    rows, columns = list(map(int,input().split())) #input no. of row and column
    b=[]
    for i in range(rows):
        a=list(map(int,input().split()))
        b.append(a)
    print(b)
    

    input

    2 3
    1 2 3
    4 5 6
    

    output [[1, 2, 3], [4, 5, 6]]

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