Python 中的 map, reduce, zip, filter, lambda基本使用方法

map(function, sequence[, sequence, ...]

该函数是对sequence中的每个成员调用一次function函数,如果参数有多个,则对每个sequence中对应的元素调用function。

返回值为一个列表

如: def func(x): return x + 10;

         map(func, [1,2,3])

         输出为[11,12,13]

又如: def func(x, y) : return x * 10 + y;

            map(func, [1,2], [3,4])

            输出为: [13, 24]

第一个例子又可以写成:

        map(lambda x : x + 10, [1, 2, 3])

第二个例子可以写成:

        map(lambda x, y : x * 10 + y, [1,2], [3,4])

这就是lambda的基本使用方法,常用来定义短小的函数。


reduce(function, sequence[, init]);

如果没有init, reduce第一次是对sequence中的前两个元素调用function, 之后每次使用上一次返回的结果和sequnce中的下一个元素来调用function. 这里function是一个二元函数

如: reduce (lambda x, y : x + y, [1, 2, 3])

        结果为: 6

又如:reduce (lambda x, y : x + y, [1,2,3], 1)

        结果为:7


filter(function or None, sequnce);

这里的function是一个布尔函数,filter对每个sequnce中的元素调用function, 返回结果为真的元素,如果sequnce是tuple,string, 那么返回类型也为tuple或string, 否则返回一个list


zip(seq1 [, seq2 [...]])                                  
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]  

Return a list of tuples, where each tuple contains the i-th  
element from each of the argument sequences.  The returned list is   truncated  in length to the length of the shortest argument sequence.

原文地址:https://www.cnblogs.com/Stomach-ache/p/3703163.html