How can I read inputs from a user and create a 2-D list?

I created a 2D array like:

>>> a = [[0 for col in range(3)] for row in range(3)]

      

then

>>> for i in range(3):
...       for j in range(3):
...           a[i][j]=input()
...

1 2 3
4 5 6
7 8 9

      

but it fails, python thinks "1 2 3" is one item and how can I do that in the form above? Thanks for any help.

+3


source to share


4 answers


You don't need to create a list in advance. You can directly create them in a list comprehension, for example

>>> a = [[int(item) for item in input().split()] for row in range(3)]
1 2 3
4 5 6
7 8 9
>>> a
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

      



Here, when called input

, whatever we will enter will be treated as a single line ( '1 2 3'

) and split

a string of whitespace characters (to get ['1', '2', '3']

) and convert each of the split string to an integer, with a function int

.

+3


source


You can split values ​​like this:



for i in range(3):
    a[i] = input().split(' ')

      

+1


source


You can split and match against int in your first comp list, you don't need to create the list first, although remember that casting to int will cause your program to crash for invalid input:

a = [list(map(int,input().split())) for row in range(3)]

print(a)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

      

Of course, if you don't want the ints to just be separated by spaces:

 a = [input().split() for row in range(3)]
 [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

      

+1


source


To enter spatial separation, you need to split the input text into " "

a=[[0 for col in range(3)] for row in range(3)]

for i in range(3):
    a[i][0], a[i][1], a[i][2] = map(int, raw_input().split())

print a

      

+1


source







All Articles