How ro read mutli lined input into 2d arrays in python

前端 未结 2 443
野的像风
野的像风 2021-01-28 22:43

I\'ve been across a problem in python, the input format of the 2d array to be read is

3           # number of rows and columns of a square matrix
1 2 3       #          


        
相关标签:
2条回答
  • 2021-01-28 23:03

    If the numbers are separated by a single space your can use the following code:

    n = int(input())
    matrix = []
    for i in range(n):
      row = [int(x) for x in input().split()]
      matrix.append(row)
    

    If you have different separator then space you can put as argument in the split() function.

    0 讨论(0)
  • 2021-01-28 23:25
    n = int(input())
    matrix = dict()
    for i in range(n):
        matrix["row"+str(i)] = input().split() # i assume you want the numbers seperated too
    

    this take the number of lines input you want makes a dictionary with the number of inputs you initialy said

    so matrix the dicitonary is now

    {'row0': ['1', '2', '3', '4'], 
    'row1': ['3', '4', '6', '9'], 
    'row2': ['4', '6', '3', '1']}
    

    incase you want them stored as intergers

    n = int(input())
    matrix = dict()
    for i in range(n):
        matrix["row"+str(i)] = [int(i) for i in input().split()]
    

    output

    {'row0': [1, 2, 3, 4], 
    'row1': [3, 4, 6, 9], 
    'row2': [4, 6, 3, 1]}
    

    or as a oneliner that just output list of lists

    [[int(i) for i in input().split()] for _ in range(int(input()))]
    

    output

    [[1, 2, 3, 4], [3, 4, 6, 9], [4, 6, 3, 1]]
    

    or as a dictionary oneliner

    {'row'+str(q) : [int(i) for i in input().split()] for q in range(int(input()))}
    

    output

    {'row0': [1, 2, 3, 4], 'row1': [3, 4, 6, 9], 'row2': [4, 6, 3, 1]}
    

    and as Patric pointed out a fast oneliner could be

    {q : [int(i) for i in input().split()] for q in range(int(input()))}
    

    output

    {1: [1, 2, 3, 4], 2: [3, 4, 6, 9], 3: [4, 6, 3, 1]}
    

    this solution is faster because dictionaries uses hashes, and thus dont have to loop through the whole list before getting to the desired index.

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