我是python的新手,正在使用python3。我正在学习numpy,但不知道如何从一行中获取用户输入。类似输入-->1 2 3 4
我试过使用这个命令,我通常用于普通数组方法,而不是numpy
from numpy import *
arr=array([])
p=1
arr=list(map(int,append(arr,input().split())))
print(arr)
但问题是,这将把我的数组变成一个列表,当我使用命令时
print(arr.dtype)
它给了我这个错误-->"列表"对象没有属性"dtype">
所以,我的问题是,在使用numpy数组模块时,如何从单行获取输入?
您应该:
- 将输入字符串拆分为一个列表
- 将列表转换为numpy数组
代码可以是:
arr = np.array(input().split(), dtype='int')
这与阵列模块相同,只是您必须明确地将值转换为积分类型:
arr = array.array('i', map(int, input().split()))
使用numpy模块中的内置函数"asarray">
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
您应该在输出中看到类似的内容。
<class 'numpy.ndarray'>
int32
[1 2 3 4 5]
我希望它有帮助。