lambda
有別於function的寫法,lamda用過即丟,用來建立簡單的function>>> test = lambda x,y,z: x*y*z >>> test(1,2,3) 6
filter
用filter函數把不符條件的element濾掉>>> a = [31,545,21,2,0,231,56] >>> func = lambda x: x>2 >>> filter(func,a) [31, 545, 21, 231, 56]
map
用map函數計算每個member的結果>>> a = [31,545,21,2,0,231,56] >>> func = lambda x: x+2 >>> map(func, a) [33, 547, 23, 4, 2, 233, 58]
reduce
用reduce計算$f(f...f(f(x_{0},x_{1}),x_{2})..,x_{n})$>>> a = [1,2,3,4,5] >>> func = lambda x,y: x*y >>> reduce(func, a) 120
range & xrange
用range 函數來產生數列
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
xrange函數用在迴圈中加強效能
>>> for i in xrange(10): print(i) 0 1 2 3 4 5 6 7 8 9
iterate寫法
iterate寫法是python特有的解決方案,和for loop類似[i*5 for i in xrange(4)] [0, 5, 10, 15]
沒有留言:
張貼留言