晓夏

YoungCheung

Zhang Sir's technical way

Python 特殊语法:filter、map、reduce、lambda

浏览量:861

Python内置了一些特殊函数,这些函数很具python特性。可以让代码更加简洁。

可以看例子:

1 filter(function, sequence):

str = ['a', 'b','c', 'd']
def fun1(s): 
    return s if s != 'a' else None
    ret = filter(fun1, str)
    print ret
## ['b', 'c', 'd']

对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于sequence的类型)返回。

可以看作是过滤函数。

2 map(function, sequence) 

str = ['a', 'b','c', 'd'] 
def fun2(s): 
    return s + ".txt"
    ret = map(fun2, str)
    print ret
## ['a.txt', 'b.txt', 'c.txt', 'd.txt']

对sequence中的item依次执行function(item),见执行结果组成一个List返回:map也支持多个sequence,这就要求function也支持相应数量的参数输入:

def add(x, y): 
    return x+y 
    print map(add, range(10), range(10)) 
##[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

3 reduce(function, sequence, starting_value):

def add1(x,y): 
    return x + y
    print reduce(add1, range(1, 100))
print reduce(add1, range(1, 100), 20)
## 4950 (注:1+2+...+99)
## 4970 (注:1+2+...+99+20)

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

4 lambda:

g = lambda s: s + ".fsh"
print g("haha")
print (lambda x: x * 2) (3)
## haha.fsh
## 6

这是Python支持一种有趣的语法,它允许你快速定义单行的最小函数,类似与C语言中的宏,这些叫做lambda的函数.


神回复

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。