Python碎片化知识:map,reduce,lambda以及zip

来源:互联网 发布:java web 照片上传 编辑:程序博客网 时间:2024/06/05 14:27

Python函数式编程

  • map
  • reduce
  • lambda
  • zip

1. map(function, iterable, …)

Python doc 中的描述:
”map(function, iterable, …)
Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list. ”

重点:map**第二个参数必须是iterable**(如list,tuple等,否则会报错),map返回的总是一个list(如果function返回多个值,那么将被返回为一个tuple),map可以有多个参数(iterable),相应的function也要有这么多的形参,下面是例子。

def foo(x):    return pow(x,2)def bar(x,y):    return x+ydef sasaki(x,y):    return x+y, x-yprint map(foo,(1,2,3))  # [1,4,9]print map(foo, [1,2,3]) # [1,4,9] # 返回的总是一个listprint map(bar,(1,2,3),(4,5,6)) # [5, 7, 9]print map(sasaki,(1,2,3),(4,5,6)) # [(5, -3), (7, -3), (9, -3)]# output[1, 4, 9][1, 4, 9][5, 7, 9][(5, -3), (7, -3), (9, -3)]

下面的会报错

print map(foo,2)# outputTypeError                                 Traceback (most recent call last)<ipython-input-16-3cbe41a8b14c> in <module>()----> 1 print map(foo,2)TypeError: argument 2 to map() must support iteration

2. reduce

Python doc :
”reduce(function, iterable[, initializer])
Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned. Roughly equivalent to: ”

def reduce(function, iterable, initializer=None):    it = iter(iterable)    if initializer is None:        try:            initializer = next(it)        except StopIteration:            raise TypeError('reduce() of empty sequence with no initial value')    accum_value = initializer    for x in it:        accum_value = function(accum_value, x)    return accum_value

我的理解,其实就是迭代,注意的是,function形参个数是2个。下面是例子:

print reduce(lambda x,y: x+y, [1,2,3,4,5]) # 迭代过程 (((1+2)+3)+4)+5 = 15

3. lambda

这是一个很好用的关键词,对于简单的函数可以变得简洁方便很多。

a = lambda x,y : [x+y, x-y]b = lambda x,y : (x+y, x-y)a(2,3) # [5, -1]b(2,3) # (5, -1)(lambda x: x**2)(3) #  9

4. zip

zip([iterable, …])
This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments which are all of the same length, zip() is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.”

注意的是,参数必须是iterable,但是最后返回的一定是list。请看例子:

x = [1,2,3]y = [4,5,6]xx = (1,2,3)yy = (4,5,6)print zip(x,y)    # [(1, 4), (2, 5), (3, 6)]print zip(xx,yy)  # [(1, 4), (2, 5), (3, 6)]print zip(x,y,xx) # [(1, 4, 1), (2, 5, 2), (3, 6, 3)]

Note:zip的两个形参(或者多个)如果满足某种函数关系,那么zip与map就非常相似了。比如上例中,y = x + 3, 请看例子:

x = [1,2,3]y = [4,5,6]print zip(x,y)                  # [(1, 4), (2, 5), (3, 6)]print map(lambda x: (x,x+3), x) # [(1, 4), (2, 5), (3, 6)]

备注

第一次写博客,哪里有什么不妥,还请看到的同学不吝赐教。

0 0
原创粉丝点击