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

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

    you can accept a 2D list in python this way ...

    simply

    arr2d = [[j for j in input().strip()] for i in range(n)] 
    # n is no of rows
    


    for characters

    n = int(input().strip())
    m = int(input().strip())
    a = [[0]*n for _ in range(m)]
    for i in range(n):
        a[i] = list(input().strip())
    print(a)
    

    or

    n = int(input().strip())
    n = int(input().strip())
    a = []
    for i in range(n):
        a[i].append(list(input().strip()))
    print(a)
    

    for numbers

    n = int(input().strip())
    m = int(input().strip())
    a = [[0]*n for _ in range(m)]
    for i in range(n):
        a[i] = [int(j) for j in input().strip().split(" ")]
    print(a)
    

    where n is no of elements in columns while m is no of elements in a row.

    In pythonic way, this will create a list of list

提交回复
热议问题