I used Jupyter notebook, I am new to Python, I try to fetch value from user in multidimensional array how I do that? I write a little code, after put first value I get error that I don't understand
Error:
Traceback (most recent call last)
in
5 for i in range(lengthrow):
6 for j in range(lengthcol):
----> 7 arr[i][j]=int(input("enter value"))
8 print(arr)
IndexError: index 0 is out of bounds for axis 0 with size 0
code:
from numpy import*
arr = array([[],[]])
lengthrow=int(input("enter array row length"))
lengthcol=int(input("enter array col length"))
for i in range(lengthrow):
for j in range(lengthcol):
arr[i][j]=int(input("enter value"))
print(arr)
解决方案
I took @Austin great answer and made some little changes:
import numpy as np
n_rows = int(input("Enter number of rows: "))
n_cols = int(input("Enter number of columns: "))
arr = [[int(input("Enter value for {}. row and {}. column: ".format(r + 1, c + 1))) for c in range(n_cols)] for r in range(n_rows)]
print(np.array(arr))
The output is:
Enter number of rows: 2
Enter number of columns: 3
Enter value for 1. row and 1. column: 1
Enter value for 1. row and 2. column: 2
Enter value for 1. row and 3. column: 3
Enter value for 2. row and 1. column: 4
Enter value for 2. row and 2. column: 5
Enter value for 2. row and 3. column: 6
[[1 2 3]
[4 5 6]]
You got an exception, because you initialized an empty array and used invalid indices. With this answer you generate the array after you have entered the users input.
Here is the long version of the one-liner (arr = [[...) which gives you the same result:
outer_arr = []
for r in range(n_rows):
inner_arr = []
for c in range(n_cols):
num = int(input("Enter value for {}. row and {}. column: ".format(r + 1, c + 1)))
inner_arr.append(num)
outer_arr.append(inner_arr)
print(np.array(outer_arr))