如何在nxn矩阵的numpy矩阵中添加来自用户的元素?

2024-04-26 22:50:33 发布

您现在位置:Python中文网/ 问答频道 /正文

from numpy import matrix

new = matrix([raw_input("enter element in matrix. . ")]) # add element from user

从用户获取行大小和列大小等在c矩阵中如何使用numpy输入nxn矩阵

^{pr2}$

Tags: 用户infromimportnumpyaddnewinput
2条回答

可以使用eval将用户给定的字符串计算为Python对象。如果您提供3x3矩阵的列表格式,矩阵可以从那里得到它。在

小心点。在代码中使用eval会让人提供恶意命令。如果这是生产代码,这可能不是一个好主意。在

>>> new = matrix([eval(raw_input("enter matrix: "))])
enter matrix: [1,2]
>>> new
matrix([[1, 2]])

与另一个答案相反,我将使用ast.literal_eval而不是内置的eval,因为它更安全。如果需要,可以让用户提前输入(n,m)矩阵维。检查元素的数量是否与预期相符也是一个好主意!这一切的一个例子是:

import numpy as np
import ast

# Example input for a 3x2 matrix of numbers
n,m = 3,2
s = raw_input("Enter space sep. matrix elements: ")

# Use literal_eval
items  = map(ast.literal_eval, s.split(' '))

# Check to see if it matches
assert(len(items) == n*m)

# Convert to numpy array and reshape to the right size
matrix = np.array(items).reshape((n,m))

print matrix

输出示例:

^{pr2}$

相关问题 更多 >