Python中的矩阵实现
其语法为:
a=[[random.random() for col in range(number of column)] for row in range(number of row)]
在这里,我们需要将随机文件导入为random()使用方法。
1)矩阵创建
编程以m*n输入矩阵并以矩阵格式打印数字。
import random
m = input("Enter No. of rows in the matrix: ")
n = input("Enter No. of columns in the matrix: ")
a = [[random.random() for col in range(n)] for row in range(m)]
print "Enter elements: "
for i in range(m):
    for j in range(n):
        a[i][j] = input()print "output is"
for i in range(m):
 for j in range(n):
    print a[i][j], '\t',
 print输出结果
Input: Enter No. of rows in the matrix: 3 Enter No. of columns in the matrix: 3 Enter elements: 1 2 3 8 6 3 7 3 5 Output: output is 1 2 3 8 6 3 7 3 5
2)矩阵加法
假设A和B是m*n个矩阵。A和B的总和,记为A+B,是通过将A和B中的相应元素相加而获得的m*n矩阵。
import random
m1=input("Enter No. of rows in the first matrix: ")
n1=input("Enter No. of columns in the first matrix: ")
a=[[random.random()for col in range(n1)]for row in range(m1)]
print "Enter Elements: "
for i in range(m1):
    for j in range(n1):
        a[i][j]=input()m2=input("Enter No. of rows in the second matrix: ")
n2=input("Enter No. of columns in the second matrix: ")
b=[[random.random()for col in range(n2)]for row in range(m2)]
print "Enter Elements: "
for i in range(m2):
    for j in range(n2):
        b[i][j]=input()c=[[random.random()for col in range(n1)]for row in range(m1)]
if ((m1==m2) and (n1==n2)):
    print "output is"
    for i in range(m1):
        for j in range(n1):
            c[i][j] = a[i][j] + b[i][j]
            print c[i][j], '\t',
        print
else:
    print "Matrix addition not possible"Enter No. of rows in the first matrix: 2 Enter No. of columns in the first matrix: 3 Enter Elements: 1 2 3 4 5 6 Enter No. of rows in the second matrix: 2 Enter No. of columns in the second matrix: 3 Enter Elements: 1 2 3 4 5 6 Output: output is 2 4 6 8 10 12
