zoukankan      html  css  js  c++  java
  • Python学习第九课——匿名函数

    匿名函数

    # 匿名函数
    func = lambda x: x + 1  # x表示参数  x+1表示处理逻辑
    print(func(10))  # 输出结果为11
    
    # 例:如何将name="hanhan" 改为 hanhan_shuai的形式
    
    # 普通函数写法
    name = "hanhan"
    
    
    def change_name(x):
        return name + '_shuai'
    
    
    res = change_name(name)
    print(res)  # 输出结果 hanhan_shuai
    
    # 匿名函数写法
    
    fun = lambda x: x + '_shuai'
    print(fun(name))  # 输出结果 hanhan_shuai
    
    # 匿名函数也可以返回多个值
    
    f = lambda x, y, z: (x + 1, y + 1, z + 4)
    print(f(1, 2, 3))  # 输出结果 (2, 3, 7)

    reduce函数

    # 利用reduce函数完成列表中元素的累加
    num = [1, 2, 3, 4, 5]
    # 用之前要先导入
    from functools import reduce
    
    #   reduce(function, sequence[, initial]) -> value
    res = reduce(lambda x, y: x + y, num, 1)  # 第一个参数是函数
    res1 = reduce(lambda x, y: x + y, num, 0)  # 第二个是逻辑运算,第三个是起始值
    res2 = reduce(lambda x, y: x + y, num)  # 默认为0
    print(res) # 输出结果 16
    print(res1) # 输出结果 15
    print(res2) # 输出结果 15

    filter函数

    #例:将看电影列表人中过滤掉以‘sb’结尾的名字,用filter实现。
    
    # filter(function or None, iterable) --> filter object
    movie_people = ['alex_sb', 'wupeiqi_sb', 'linhaifeng', 'yuanhao_sb']
    li = filter(lambda n: not n.endswith('sb'), movie_people)
    print(list(li)) # 输出结果 ['linhaifeng']

    map函数

    # map函数  map(func, *iterables) --> map object
    # 用map实现将列表中的值叠加1
    num = [1, 2, 3, 4, 5]
    res = map(lambda x: x + 1, num)  # map第一个参数为处理方法,第二个参数为可迭代对象
    print(res)
    # for i in res:
    #     print(i)
    print(list(res))  # 输出结果 [2, 3, 4, 5, 6]
    
    # 用map实现将小写转大写
    
    st = "hanhanshigeshuaige"
    
    res1 = map(lambda x: x.upper(), st)
    print(list(res1))

    一些常用的内置函数

    print(abs(-1))  # 取绝对值
    
    print(bin(20))  # 将十进制转换为二进制
    print(hex(12))  # 10进制->16进制
    print(oct(12))  # 10进制->8进制
    
    name = '憨憨好'
    print(bytes(name, encoding='utf-8'))  # 将字符串转换为字节
    print(bytes(name, encoding='utf-8').decode('utf-8'))  # 解码 将字节转化为字符串

    总结

    # map() 处理序列中的每个元素,得到的结果是一个‘列表’,读‘列表’元素个数及位置与原来一样

    # filter() 遍历序列中的每个元素,判断每个元素得到布尔值,如果是True就留下来。

    # reduce() 处理一个序列,然后把序列进行合并操作
  • 相关阅读:
    SAP分析云及协同计划
    使用SSH命令行远程登录运行在CloudFoundry上的应用
    如何远程调试部署在CloudFoundry平台上的nodejs应用
    Apache httpclient的execute方法调试
    如何用Java代码在SAP Marketing Cloud里创建contact数据
    nodejs request module里的json参数的一个坑
    如何在调用Marketing Cloud contact创建API时增加对扩展字段的支持
    Efim and Strange Grade
    Vitya in the Countryside
    Anatoly and Cockroaches
  • 原文地址:https://www.cnblogs.com/pyhan/p/12228089.html
Copyright © 2011-2022 走看看