# python中lambda函数 list comprehension 和

lambda 函数

Python 支持一种有趣的语法，它允许你快速定义单行的最小函数。这些叫做 lambda 的函数，是从 Lisp 借用来的，可以用在任何需要函数的地方。

def f(x): return x*2，用lambda函数来替换可以写成：g = lambda x: x*2`g(3)结果是6.(lambda x: x*2)(3)`也是同样的效果。

testList = [1,2,3,4]
def mul2(x):
print x*2
[mul2(i) for i in testList]
[mul2(i) for i in testList if i%2==0]

multilist = [[0 for col in range(5)] for row in range(3)]

zip 函数

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c)
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped)
[(1, 2, 3), (4, 5, 6)]

m = [[-1.0, 2.0/c-1, -2.0/c+1, 1.0],
[2.0, -3.0/c+1, 3.0/c-2, -1.0],
[-1.0, 0.0, 1.0, 0.0],
[0.0, 1.0/c, 0.0, 0.0]]
multiply = lambda x: x*c
m = [[multiply(m[col][row]) for col in range(4)] for row in range(4)]
print [[m[col][row] for col in range(4)] for row in range(4)]

print [[multiply(each) for each in row] for row in m]更加pythonic

def matrixMul(A, B):
res = [[0] * len(B[0]) for i in range(len(A))] for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
res[i][j] += A[i][k] * B[k][j] return res
def matrixMul2(A, B):
return [[sum(a * b for a, b in zip(a, b)) for b in zip(*B)] for a in A]

a = [[1,2], [3,4], [5,6], [7,8]]
b = [[1,2,3,4], [5,6,7,8]]
print matrixMul(a,b) print matrixMul(b,a) print "-"*90
print matrixMul2(a,b) print matrixMul2(b,a) print "-"*90

QQ号联系： 360901061

【本文对您有帮助就好】