Turing101
Turing101

Reputation: 377

How to take user input from a single line in NumPy array?

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

Answers (2)

break-pointt
break-pointt

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

Serge Ballesta
Serge Ballesta

Reputation: 148880

You should:

  1. split the input string into a list
  2. convert the list to a numpy array

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

Related Questions