您的位置:首页 > 编程语言 > Python开发

[Python] 函数lambda(), filter(), map(), reduce()

2013-05-10 20:30 1191 查看

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()

map(function, sequence) :对sequence中的item依次执行function(item),见执行结果组成一个List返回:

>>> 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()

reduce(function, sequence, starting_value):对sequence中的item顺序迭代调用function,如果有starting_value,还可以作为初始值调用,例如可以用来对List求和:

>>> 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))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: