1

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?

1
  • have u imported numpy module? I have done --> from numpy import * Commented Apr 16, 2020 at 9:27

2 Answers 2

1

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()))
Sign up to request clarification or add additional context in comments.

1 Comment

another question, what to do while using the array module instead of the numpy module for the same problem, that is taking the input from the same line, what I had done is this, from array import * arr=array('i',[]) arr = list(map(int, input().split())) print(arr) but it is turning my array to list again
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.