zoukankan      html  css  js  c++  java
  • python--004--函数(map、filter、reduce)

    1. map 函数
    # 实现指定列表自增1
    num_1 = [1, 2, 10, 5, 6, 8]
    
    def map_test(func, array):
        ret = []
        for i in array:
            res = func(i)
            ret.append(res)
        return ret
    
    
    print(map_test(lambda x: x + 1, num_1))
    # 这就是python提供的map所实现的功能
    print('内置函数map,处理结果', map(lambda x: x + 1, num_1))
    # output: [2, 3, 11, 6, 7, 9]
    # 内置函数map,处理结果 <map object at 0x00000000027933C8>    ,返回的是迭代器,只能处理一次
    res = map(lambda x: x + 1, num_1)
    print(list(res))
    # output;[2, 3, 11, 6, 7, 9]


    2、 filter函数
    movie_people = ['peiqi_ab', 'qiaozhi_ab', 'suxi_ab', 'cat']
    print(filter(lambda n: n.endswith('ab'), movie_people))
    print(list(filter(lambda n: n.endswith('ab'), movie_people)))

    3、reduce函数 ---python2中直接用
    from functools import reduce ---python3中使用reduce函数需要导入

    from functools import reduce
    
    num_1 = [1, 2, 10, 5, 6, 8]
    print(reduce(lambda x, y: x + y, num_1, 1))     # 最后一个值为附的初始值


    4、区别

    map:处理序列中的每个元素,得到的结果是一个“列表”,该“列表”元素个数及位置与原来一样
    filter:遍历序列中的每个元素,判断每个元素得到一个布尔值。如果是true则保留
    reduce:处理一个序列,然后把序列进行合并操作



  • 相关阅读:
    decode函数
    下载
    sed命令
    JAVA中常用IO流类:FileInputStream和FileOutputStream
    /etc/sysconfig/i18n文件详解
    myeclipse注册方法
    Python标准库os的使用方法
    Python三方库PyAutoGUI的使用方法
    php获取文件创建时间、修改时间
    PHP获取今天、昨天、明天的日期
  • 原文地址:https://www.cnblogs.com/jinf/p/10633903.html
Copyright © 2011-2022 走看看