Python中的map、zip、reduce、filter的用法

    Hurray 1255次浏览 0条评论 2460字

#Python

> Python中对于矩阵的操作一般使用Numpy等库会比较方便。在没有这些库的时候,可以使用原生的map、zip、reduce、filter来操作。 ##定义和举例 ### map > Return an iterator that applies function to every item of iterable, yielding the results > map(func, iterableVia)等价于:[func(item) for item in iterableVia]。 例如: ```python a = map(sum, ([1, 2], [3, 4], [5, 6])) # a = [3, 7, 11] b = map(lambda x : x*x, range(6)) # b = [0, 1, 4, 9, 16, 26] ``` ### zip > Make an iterator that aggregates elements from each of the iterables > 如果需要对压缩过的对象(list)进行解压(list-->tuple),只需要在之前添加一个星号* > zip(a, b, c, )等价于[(a[0], b[0], c[0],), (a[1], b[1], c[1]), ...] 例如: ```python a = zip([1, 2, 3], [4, 5, 6], [7, 8, 9]) # a = [(1, 4, 7), (2, 5, 8), (3, 6, 9)] b = zip([1, 2, 3], [4, 5, 6], [7, 8, 9, 10]) # b = [(1, 4, 7), (2, 5, 8), (3, 6, 9)] ``` ### reduce > 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. > 即递归。reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5)。 例如: ```python reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) # 15 ((((1+2)+3)+4)+5) reduce(lambda x, y: x+y, [1, 2, 3, 4, 5], 100) # 115 (((((100+1)+2)+3)+4)+5) ``` ### filter > Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list. 例如: ```python a = filter(lambda x:x>2, [1, 2, 3, 4]) # [3, 4] b = filter(None, [-1, 0, 1, 2]) # [-1, 1, 2] ``` ### list > list(var) 等价于 [item for item in var] ## 组合用法 ### 二维矩阵 行列交换 ```python a = [[1,2,3], [4,5,6], [7,8,9]] zip(*a) # [(1, 4, 7), (2, 5, 8), (3, 6, 9)] map(list, zip(*a)) # [[1, 4, 7], [2, 5, 8], [3, 6, 9]] ``` ### 二维矩阵 旋转:顺时针旋转90° ``` a = [[1,2,3], [4,5,6], [7,8,9]] map(list, zip(*a[::-1])) #[[7, 4, 1], [8, 5, 2], [9, 6, 3]] ```

最后修改: