Home > Software design >  Take input for list of numpy array in python
Take input for list of numpy array in python

Time:10-29

in below code I have hard coded the values in my list which included numpy arrays, I want to take this as input from user. Like it should ask for number of x and then user should enter x1,x2...xn accordingly. Thank you.

x=[np.array([[1],[-2],[0],[-1]]),np.array([[0],[1.5],[-0.5],[-1]]),np.array([[-1],[1],[0.5],[-1]])]

CodePudding user response:

I finally figured it out with the help of a friend, please refer below code if anyone encountered same problem:

n=int(input())  
x=list()  
for i in range(n):  
   x.append(mm.array(list(map(float, input().split()))))  
   x[i]=x[i].reshape(4,1)  
print(x)

CodePudding user response:

So you want a list for all the x values. The link I commented gives you the user input which you can loop through to get all the values of x you want. You should be checking that the user input is valid (a real number, a reasonable number etc).

import numpy as np

#Get x (make sure x is good value)
x_total = int(input("Enter x:"))
list_x = [None] * x_total
np_x = np.zeros(x_total) # using numpy

for i in range(x_total):
    list_x[i] = input(f'Enter x {i}')
    np_x[i] = list_x[i]

print("List: ",list_x)
print("Np Array: ", np_x)

Now you have a list with n values of x.

Edit: if you want, you could have the user type in a string of number's separated by spaces or whatever you want and parse them into a list instead of asking one by one. Whatever fits your scenario best.

  • Related