Reputation: 2946
I have created a 2-dimensional 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 doesn't success,python think '1 2 3' is one element,and how can I do that in above form?Thanks for any help.
Upvotes: 3
Views: 70
Reputation: 180411
You can split and map to int in your first list comp, you don't need to create the list first, although bear in mind casting to int will make your program 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 ints just split on whitespace:
a = [input().split() for row in range(3)]
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
Upvotes: 1
Reputation: 239473
You don't have to create the list before-hand. You can directly create them in the list comprehension like this
>>> 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, whenever input
is called, whatever we feed in will be read as a single string ('1 2 3'
) and we split
the string on the whitespace characters (to get ['1', '2', '3']
) and convert each of the split string to integer, with int
function.
Upvotes: 3
Reputation: 22954
For taking space separated input you need to split the input text on " "
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
Upvotes: 1
Reputation: 10135
You can split values like this:
for i in range(3):
a[i] = input().split(' ')
Upvotes: 1