2016-12-29 83 views
0
# 3x3 
X = [[0,0,0], 
    [0 ,5,6], 
    [7 ,0,0]] 
# 3x4 
Y = [[0,0,0,0], 
    [0,0,0,0], 
    [0,0,0,0]] 
# 3x4 
result = [[0,0,0,0], 
     [0,0,0,0], 
     [0,0,0,0]] 

# iterate through rows of X 
for i in range(len(X)): 
    # iterate through columns of Y 
    for j in range(len(Y[0])): 
     # iterate through rows of Y 
     for k in range(len(Y)): 
      result[i][j] += X[i][k] * Y[k][j]   
#This code multiplies matrices X and Y and puts the resulting product into matrix result 
#It then prints the matrix result row by row, so it looks like a matrix on the screen 
for r in result: 
    print(r) 

在这里,我有一个计划,将制定出一个矩阵,但我不知道如何运行程序时,而不是事先输入的数字矩阵程序要求用户输入

+3

什么“用户输入蟒蛇”在搜索引擎回报? –

+1

http://stackoverflow.com/questions/32466311/taking-nn-matrix-input-by-user-in-python –

+0

一种自然的方法是让用户输入字符串,如'[[1,2],[ 3,4]]'然后解析这些字符串(这很简单)。 –

回答

0

询问用户输入一种特别简单的方法来从所述用户获得的两个矩阵是从模块ast使用函数literal_eval

import ast 
X = ast.literal_eval(input("Enter the first matrix as a list of lists: ")) 
Y = ast.literal_eval(input("Enter the second matrix: ")) 
#code to compute X*Y -- note that you can't hard-wire the size of result 

这种方法的优点在于,如果用户在提示进入[[1,2],[3,4]](其产生字符串'[[1,2],[3,4]]')然后literal_eval将此字符串转换为列表[[1,2],[3,4]]

要使此方法健壮,您应该使用错误陷印来优雅地处理用户例如错误地输入[[1,2][3,4]]

至于不硬布线的result大小:由于该产品是由行填充行,我建议通过初始化result的,因为他们计算这些附加行空单重构你的代码。作为一个模板是这样的:

result = [] 
for i in range(len(X)): 
    row = [0]*len(Y[0]) 
    for j in range(len(Y[0])): 
     # code to compute the jth element of row i 
    result.append(row)