def f(x): return x*2
,用lambda函數來替換能夠寫成:g = lambda x: x*2``g(3)結果是6
. (lambda x: x*2)(3)
也是一樣的效果。
我將它們用在須要封裝特殊的、非重用代碼上,避免令個人代碼充斥着大量單行函數。
看一段簡單代碼html
<!-- lang: python -->python
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)]
函數
<!-- lang: python --> >>> 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)]
<!-- lang: python --> 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)]
它所做的工做:m是一個包含參數c的矩陣,他計算了c*m的結果 > 想了一下,最後一句改爲 <pre><code>print [[multiply(each) for each in row] for row in m]</code></pre>更加pythonic學習
學習資源 <!-- lang: python --> 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.net
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