Reputation: 377
I am new to python and I am using python3 . I am learning numpy but cant figure out how to take user input from a single line. Like inputs--> 1 2 3 4
I have tried using this command which I generally used for normal array method other than numpy
from numpy import *
arr=array([])
p=1
arr=list(map(int,append(arr,input().split())))
print(arr)
But the problem with this is that this is turning my array into a list and when I am using the command
print(arr.dtype)
It gives me this error--> 'list' object has no attribute 'dtype'
So, my question is how to take input from a single line while using the numpy array module?
Upvotes: 1
Views: 2919
Reputation: 21
use the built-in function "asarray" from numpy module
import numpy as np
# use asarray function of the numpy module. you can directly assign the data type too
usrInput = np.asarray(input().split(), dtype=np.int32)
print(type(usrInput)) # checking the type of the array
print(usrInput.dtype) # check the data type
print(usrInput) # display the output
you should see something like this in the output.
<class 'numpy.ndarray'>
int32
[1 2 3 4 5]
I hope it's helpful.
Upvotes: 1
Reputation: 148880
You should:
Code could be:
arr = np.array(input().split(), dtype='int')
This is the same for the array module, except that you must explicitely convert the values to an integral type:
arr = array.array('i', map(int, input().split()))
Upvotes: 1