我试图从用户输入中获取 numpy 二维数组,但它无法正常工作,因为 input() 返回“str”类型,而 numpy array() 方法需要一个元组:
import numpy as N
def main():
A = input() # the user is expected to enter a 2D array like [[1,2],[3,4]] for example
A = N.array(A) # since A is a 'str' A
print(A.shape) # output is '()' instead of '(2, 2)' showing the previous instruction didn't work as expected
if __name__ == "__main__":
main()
所以我的问题是:如何将输入字符串转换为元组,以便 array() 方法正确地将输入转换为 numpy 2D 数组?
提前致谢。
以下交互式会话在我的案例中运行良好:
>>> A = input()
[[1, 2], [3, 4]]
>>>
>>> A
[[1, 2], [3, 4]]
>>> type(A)
<type 'list'>
>>> import numpy
>>> numpy.array(A)
array([[1, 2],
[3, 4]])
>>>
您输入的数据是否用引号引起来,即:
>>> A = input()
"[[1, 2], [3, 4]]"
>>> A
'[[1, 2], [3, 4]]'
>>> type(A)
<type 'str'>
这是我能想到的你的代码失败的唯一原因。除非用户输入一个字符串,否则输入不会返回字符串;在您的情况下,它相当于
eval(raw_input())
。
我认为代码是正确的,您需要更改输入数据的方式。请看下面的代码片段
>>> import numpy as N
>>> A = input()
((1,2),(3,4))
>>> type(A[0][0])
<type 'int'>
和Brett Lempereur
的答案仅适用于Python2,因为Python3中的input()默认会返回Sidharth Shah
。str
在 Python3 中,您还需要使用
ast
来评估列表中的字符串输入。
>>> import ast
>>> import numpy as np
>>> matrixStr = input()
[[1, 2], [3, 4]]
>>> type(matrixStr)
str
>>> matrixList = ast.literal_eval(matrixStr)
>>> type(matrixList)
list
>>> matrix = np.array(matrix)
或者简单地你可以这样做:
import numpy
def array_input():
a = eval(input('Enter list: '))
b = numpy.array(a)
return b
print(array_input())
import numpy as np
arr = np.array([[int(x) for x in input(f"Enter the value{[i]}:").split()] for i in range(3)])
print(arr)
Numpy 2D 数组用户定义输入
# Importing the NumPy library for numerical computations
import numpy as np
lis = [] # Initializing an empty list to store user input values
# Looping three times to get input for three different values
for i in range(3):
# Prompting the user to enter a value and splitting it into separate values
# based on the current iteration index i
user_input = input(f"Enter the value {[i]}:").split()
# Appending the entered values to the list
lis.append(user_input)
# Converting the list of entered values to a NumPy array with integer data type
arr = np.array(lis, dtype=int)
print(arr) # Printing the final NumPy array containing the entered values
要获得整数输入,您必须在 int() 中传递 input() 就像...
A=int(input())
type(A)
>>>int