0
from numpy import matrix

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

从用户那里获取行和列大小,就像在 c 矩阵中一样 如何使用 numpy 输入 nxn 矩阵

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

2 回答 2

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]]
于 2013-10-23T14:33:53.267 回答
0

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

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

>>> new = matrix([eval(raw_input("enter matrix: "))])
enter matrix: [1,2]
>>> new
matrix([[1, 2]])
于 2013-10-23T12:54:43.893 回答