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

时间:2013-10-22 12:33:11

标签: python numpy matrix

from numpy import matrix

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

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

matrix([for i in row: for j in col: raw_input(add >data)])

2 个答案:

答案 0 :(得分:1)

与其他答案相反,我会使用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

示例输出:

Enter space sep. matrix elements: 1 2 3 4 5 6
[[1 2]
 [3 4]
 [5 6]]

答案 1 :(得分:0)

您可以使用eval来评估用户提供给Python对象的字符串。如果以列表格式提供3x3矩阵,矩阵可以从那里获取。

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

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