码迷,mamicode.com
首页 > 编程语言 > 详细

python的reduce,map,zip和filter函数

时间:2018-02-11 14:36:04      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:print   filter   color   def   序列   使用   int   style   add   

一、    reduce(function,Iterable),它的形式和map()函数一样。不过参数function必须有两个参数

reduce()函数作用是:把结果继续和序列的下一个元素做累积计算。

例,
    
    >>>def add(x, y) :            # 两数相加
    ...     return x + y
    ...
    >>> reduce(add, [1,2,3,4,5])   # 计算列表和:1+2+3+4+5
    15
    >>> reduce(lambda x, y: x+y, [1,2,3,4,5])  # 使用 lambda 匿名函数
    15




二、    map(function,Iterable)是将列表中的每一个元素作用于函数。

1.返回值:

    Python 2.x 返回列表。

    Python 3.x 返回迭代器。
所以python3中获取map返回值的两个基本方法:
    ①print(list(map(f,Iter)))      #这里的f代表函数,Iter代表可迭代对象。
    ②使用 for 循环。


例,
    ①m = map(lambda x : x + 1, [1, 2, 3])
      print(list(m))   #结果为:[5, 7, 9]

    ②提供了两个列表,对相同位置的列表数据进行相加
      >>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
      [3, 7, 11, 15, 19]




三、    zip函数接受任意多个可迭代对象作为参数,将对象中对应的元素打包成一个tuple,然后返回一个可迭代的zip对象。
例,
    lt1 = [‘a‘, ‘b‘, ‘c‘]
    lt2 = [1, 2, 3]
    lt3 = [‘A‘, ‘B‘, ‘C‘]
    result = list(zip(lt1, lt2, lt3))
    print(result)   #输出结果:[(‘a‘, 1, ‘A‘), (‘b‘, 2, ‘B‘), (‘c‘, 3, ‘C‘)]



四、    filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。
    filter接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。
    语法:filter(function, Iterableble)

例,
    func = lambda x : x % 2 == 1
    print(list(filter(func, [1,2,3]))) #输出结果:[1, 3]

python的reduce,map,zip和filter函数

标签:print   filter   color   def   序列   使用   int   style   add   

原文地址:https://www.cnblogs.com/Downtime/p/8441048.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!