[Python] 函式lambda(), filter(), map(), reduce()
阿新 • • 發佈:2019-01-01
1、lambda()
lambda()是Python裡的匿名函式,其語法如下:
lambda [arg1[, arg2, ... argN]]: expression
下面是個1+2=3的例子
>>> fun = lambda x,y:x+y
>>> fun(1,2)
3
>>> (lambda x,y:x+y)(1,2)
3
2、filter()
filter(function, sequence):對sequence中的item依次執行function(item),將執行結果為True的item組成一個List/String/Tuple(取決於sequence的型別)返回:>>> def f(x): return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
>>> def f(x): return x != 'a'
>>> filter(f, "abcdef")
'bcdef'
3、map()
>>> def cube(x): return x*x*x
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> def cube(x) : return x + x
...
>>> map(cube , "abcde")
['aa', 'bb', 'cc', 'dd', 'ee']
另外map也支援多個sequence,這就要求function也支援相應數量的引數輸入:
>>> def add(x, y): return x+y
>>> map(add, range(8), range(8))
[0, 2, 4, 6, 8, 10, 12, 14]
4、reduce()
>>> def add(x,y): return x + y
>>> reduce(add, range(1, 11))
55 (注:1+2+3+4+5+6+7+8+9+10)
>>> reduce(add, range(1, 11), 20)
75 (注:1+2+3+4+5+6+7+8+9+10+20)
5、綜合例子
例子1:計算5!+4!+3!+2!+1!
a=[5,4,3,2,1]
def fun(x):
result = 1
while x >= 1:
result = result * x
x = x - 1
return result
print reduce(lambda x,y:x+y, map(fun,a))
例子2:將100以內的質數挑選出來
import math
def isPrime(n):
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
print filter(isPrime,range(1,100))