【Python】Python特殊语法之:filter、map、reduce、lambda(转自“玩玩python”)

来源:互联网 发布:linux系统总共有多少种 编辑:程序博客网 时间:2024/05/16 10:31

Python内置了一些非常有趣但非常有用的函数,充分体现了Python的语言魅力!

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'

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]

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)

>>> from functools import reduce>>> def add(x, y):return x + y>>> reduce(add, range(1,10), 20)65>>> 


75 (注:1+2+3+4+5+6+7+8+9+10+20)

lambda:

lambda parameters : expression

匿名函数,一种语法糖。

通常需要一个函数,只有一行语句,但又不想费神命名函数的情况下使用。

结合functional programing中的filter,map, reduce函数,可实现一些对常量进行操作的新思维模式。

这是Python支持一种有趣的语法,它允许你快速定义单行的最小函数,类似与C语言中的宏,这些叫做lambda的函数,是从LISP借用来的,可以用在任何需要函数的地方:
>>> g = lambda x: x * 2 
>>> g(3)
6
>>> (lambda x: x * 2)(3) 
6

python中的reduce内建函数是一个二元操作函数,他用来将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给reduce中的函数 func()(必须是一个二元操作函数)先对集合中的第1,2个数据进行操作,得到的结果再与第三个数据用func()函数运算,最后得到一个结果。

如:

def myadd(x,y): return x+y sum=reduce(myadd,(1,2,3,4,5,6,7)) print sum #结果就是输出1+2+3+4+5+6+7的结果即28 当然,

也可以用lambda的方法,更为简单: sum=reduce(lambda x,y:x+y,(1,2,3,4,5,6,7)) print sum    

python 3.0.0.0   reduce

今天在搜用python求阶乘的时候, 搜出来的最简单的是用reduce这个built-in function, 但是我用reduce的时候, 却报NameError: name 'reduce' is not defined. 于是又搜了一下,发现在python 3.0.0.0以后, reduce已经不在built-in function里了, 要用它就得from functools import reduce.

详见The fate of reduce() in Python 3000

reduce的用法

reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.

意思就是对sequence连续使用function, 如果不给出initial, 则第一次调用传递sequence的两个元素, 以后把前一次调用的结果和sequence的下一个元素传递给function. 如果给出initial, 则第一次传递initial和sequence的第一个元素给function.

view plaincopy to clipboardprint?
>>> from functools import reduce   
>>> reduce(lambda x,y: x+y, [1, 2, 3])   

>>> reduce(lambda x, y: x+y, [1,2,3], 9)   
15 
>>> reduce(lambda x,y: x+y, [1, 2, 3], 7)   
13 
>>> 


map(), filter(), reduce()的实现:

def map(func, seq):    mapped_seq = []    for eachitem in seq:        mapped_seq.append(func(eachitem))    return mapped_seqdef filter(func,seq):    filtered_seq = []    for eachitem in seq:        if bool_func(eachitem):            filtered_seq.append(eachitem)    return filtered_seqdef reduce(bin_func, seq, initial = None):    lseq = list(seq)    if initial is None:        res = lseq.pop(0)    else:        res = initial    for eachitem in lseq:        res = bin_func(res, eachitem)    return res


Python3.3里, map(), filter()的返回值不再是list而是iterators,如果要得到上面的结果需要list()强制转换

reduce已经remove,需要先import functools module

0 0