24 Sep 2012

Python Tips: 矩阵乘法



这是OSChina一个网友的问题
可以用一句话来完成这个乘法,也可以用循环做
#! /usr/bin/env python

def MulMatrix(a,b):
 if len(a)!=len(b[0]) or len(a[0])!=len(b):
  print 'ERROR: can\'t mul !'
  return
 return [[sum([a[i][k]*b[k][j] for k in range(len(a[0]))]) for j in range(len(b[0]))] for i in range(len(a))]


A=[[1,2],[3,4],[5,6],[7,8]]
B=[[1,2,3,4],[5,6,7,8]]
C = MulMatrix(A,B)
for i in range(len(C)):
 for j in range(len(C[0])):
  print C[i][j],
 print
结果:
11 14 17 20
23 30 37 44
35 46 57 68
47 62 77 92
[Finished in 0.1s]

No comments :

Post a Comment