Tyler Wong
Tyler Wong

Reputation: 27

Taking x number integers and putting them into an array

I need to take x amount of input lines (x is specified by the user) then put them into a 2d array. Each line contains x amount of integers separated by spaces.

For example; Input:

3

4 3 1

6 5 2

9 7 3

I need to take that input and put them into a 2d array, how do I do this?

Upvotes: 1

Views: 68

Answers (2)

rutvik5
rutvik5

Reputation: 11

Suppose you have your input stored in a file named 'input.txt'

n=2 #number specified by user

with open('input.txt', 'r') as file:
    result = [[int(char) for char in lines.split(' ')]for lines in file.read().splitlines()[:2*n:2] ]

Upvotes: 1

Vitor SRG
Vitor SRG

Reputation: 694

Assuming your numbers are separated exactly by one space:

n = int(input('enter size'))

print([[int(i) for i in input().split(' ')]
       for __ in range(n)])

Upvotes: 1

Related Questions