a = [1] * 4 b = [1,2] * 2 def original_diff(l1, l2): diff = 0 for i in range(len(l1)): if l1[i] != l2[i]: diff += 1 return diff def lambda_diff(l1, l2): return list(map(lambda x: x[0] == x[1], zip(l1, l2))).count(False)目的是要算出兩個整數list相差的元素個數,原本是用for loop一個個算,後來手癢又寫了一個lambda版本,以為會比較快,但
ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.373 0.373用原本的方法快了一倍 囧:1( ) 100000 0.093 0.000 0.093 0.000 temp.py:19(original_diff) 100000 0.173 0.000 0.234 0.000 temp.py:26(lambda_diff) 400000 0.052 0.000 0.052 0.000 temp.py:27( )
另外就是map(function, itre)做出來的是map object,必須再用list()把他轉成list,StackoverFlow上一樣的問題。
沒有留言:
張貼留言