• Python3-笔记-C-004-函数-map、filter、reduce & lambda


    f = lambda x, y, z: x + y + z
    print(f(1, 2, 3)) # 6
    g = lambda x, y=2, z=3: x + y + z
    print(g(1, z=4, y=5)) # 10

    # lambda表达式常用来编写跳转表(jump table),就是行为的列表或字典
    L = [(lambda x: x**2),
    (lambda x: x**3),
    (lambda x: x**4)]
    print(L[0](2),L[1](2),L[2](2)) # 4 8 16

    D = {'f1':(lambda: 2+3),
    'f2':(lambda: 2*3),
    'f3':(lambda: 2**3)}
    print(D['f1'](),D['f2'](),D['f3']()) # 5 6 8

    # map(function, sequence[, sequence, ...]) -> list
    # 将函数调用映射到每个序列的对应元素上并返回一个含有所有返回值的列表
    def inc(x, y):
    return (x, y)
    la = [1, 2, 3, 4]
    lb = ['Sun', 'M', 'T', 'W', 'T', 'F', 'S']
    l1 = list(map(inc, la, lb)) # <class 'list'>: [(1, 'Sun'), (2, 'M'), (3, 'T'), (4, 'W')]
    l2 = list(map((lambda x, y: x * y), la, la)) # 两个参数的 <class 'list'>: [1, 4, 9, 16]
    l3 = list(map((lambda x: x**2), la)) # 使用lambda形式 <class 'list'>: [1, 4, 9, 16]
    l4 = list(x**2 for x in range(1, 5)) #这样更快 <class 'list'>: [1, 4, 9, 16]
    l5 = list(x+y for x in range(5) if x%2 == 0 for y in range(10) if y%2 ==1)
    # <class 'list'>: [1, 3, 5, 7, 9, 3, 5, 7, 9, 11, 5, 7, 9, 11, 13]

    # filter(function or None, sequence) -> list, tuple, or string
    # 为已知的序列的每个元素调用给定的布尔函数,调用中,返回值为非零的元素将被添加至一个列表中
    def fun1(x):
    if x > 100:
    return True
    else:
    return False
    f1 = list(filter(fun1, [2, 101, 600, 3])) # <class 'list'>: [101, 600]
    f2 = list(filter(lambda x: x % 2 == 0, la)) # <class 'list'>: [2, 4]
    f3 = list(filter(lambda x: True if (x > 'a') else False, ['a', 'b', 'c'])) # <class 'list'>: ['b', 'c']

    # reduce(function, sequence[, initial]) -> value
    # (概括:把结果继续和序列的下一个元素做累积计算)
    # function参数是一个有两个参数的函数,reduce依次从sequence中取一个元素,
    # 和上一次调用function的结果做参数再次调用function。第一次调用function时,
    # 如果提供initial参数,会以sequence中的第一个元素和initial作为参数调用function
    # 否则会以序列sequence中的前两个元素做参数调用function
    from functools import reduce
    c = reduce(lambda x, y: x + y, la) # 10
    c = reduce(lambda x, y: x + y, la, 100) # 110
  • 相关阅读:
    地图相关
    爬虫机器人检测网站
    Git 工作区、暂存区和版本库概念
    linux镜像下载地址
    selenium基本使用
    socket 编程
    视频观看时间统计
    油猴脚本
    (II)第十三节:使用注解创建Dao、Service、Controller Bean 组件
    (II)第十一节:SpEL 表达式
  • 原文地址:https://www.cnblogs.com/vito13/p/7730034.html
Copyright © 2020-2023  润新知