• Python学习(七)——匿名函数、map函数、filter函数、reduce函数与其他内置函数


    匿名函数 

    1 lambda x: x + 1          
    2 # lambda:定义匿名函数的关键字      
    3 # x:形参                   
    4 # x+1:程序处理逻辑             
    5 fun = lambda x: x + 1    
    6 print(fun(5))            
    7 #6                       
    1 fun = lambda name: name + "_new"
    2 print(fun("Cindy"))             
    3 #Cindy_new                      

    注意:

    1、匿名函数一般不会单独使用,而是与其他函数配合使用

    2、匿名函数的程序处理逻辑简单,不可以使用多行

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

    函数式编程

    编程的方法论:

    1、面向过程:找到解决问题的入口,按照一个固定的流程去模拟解决问题的流程 

    2、函数式编程:编程语言定义的函数+数学意义的函数,即用编程语言去实现数学函数,返回值是函数,没有for和while循环,所有循环使用递归实现。

      特点:a.不可变数据:不用变量保存状态,不修改变量 b.第一类对象:函数即“变量” c.尾调用优化(尾递归):在函数的最后一步(不一定是最后一行)进行递归

    1 def test1(x):                             
    2     return x                              
    3 def test2(y):                             
    4     return test1(y) + 1      #不是尾递归       
    5 # 拆解:res = test1(y)                       
    6 #      return res + 1                    

    3、面向对象

    高阶函数

    满足下列任一要求即为高阶函数:

    1、函数的传入参数是一个函数名

    2、函数的返回值是一个函数名

    map函数

     1 def plus_one(x):
     2     return x + 1
     3 def minis_one(x):
     4     return x - 1
     5 def square(x):
     6     return x**2
     7 def map_test(func,num) :
     8     nl = []
     9     for i in num:
    10         nl.append(func(i))
    11     return nl
    12 
    13 num = [1,2,3,4,5]
    14 nl = map_test(square,num)
    15 print(nl)
    16 # [1, 4, 9, 16, 25]
    17 nl1 = map_test(plus_one,num)
    18 print(nl1)
    19 # [2, 3, 4, 5, 6]

    也可以写成

     1 plus_one = lambda x: x + 1 
     2 minis_one = lambda x: x - 1
     3 square = lambda x: x**2    
     4 def map_test(func,num) :   
     5     nl = []                
     6     for i in num:          
     7         nl.append(func(i)) 
     8     return nl              
     9                            
    10 num = [1,2,3,4,5]          
    11 nl = map_test(square,num)  
    12 print(nl)                  
    13 # [1, 4, 9, 16, 25]        
    14 nl1 = map_test(plus_one,num
    15 print(nl1)                 
    16 # [2, 3, 4, 5, 6]          

    最好的写法:

     1 def map_test(func,num) :            
     2     nl = []                         
     3     for i in num:                   
     4         nl.append(func(i))          
     5     return nl                       
     6                                     
     7 num = [1,2,3,4,5]                   
     8 nl = map_test(lambda x: x + 1,num)  
     9 print(nl)                           
    10 # [2, 3, 4, 5, 6]                   

    map函数

    功能:依次处理序列中的每个元素,得到的结果是一个“列表”,该“列表”元素个数及位置与原来一样

    注意:得到的结果并不是真正的列表

    1 num = [1, 2, 3, 4, 5]
    2 res = map(lambda x: x + 1, num)
    3 print(res)
    4 #<map object at 0x000002205AF765C0>
    5 print(list(res))
    6 # [2, 3, 4, 5, 6]

    map的第一个参数是处理逻辑,第二个参数是可迭代对象,得到的结果是一个可迭代对象

    1 str = "hello"
    2 res = map(lambda x: x.upper(), str)
    3 print(list(res))
    4 #['H', 'E', 'L', 'L', 'O']
    5 print(res)
    6 # <map object at 0x000002672E8282E8>

    filter函数 

    功能:遍历序列中的每个元素,判断每个元素得到布尔值,True的元素保留下来,否则过滤掉

    filter的第一个参数是处理逻辑,第二个参数是可迭代对象,得到的结果是一个可迭代对象

    前一个参数得到的结果是布尔值,是True则保留,是False则过滤掉,可以在处理逻辑处+not来反过滤

    1 array = ["Allen", "Leo", "jennifer"]
    2 res = filter(lambda x: x.istitle(), array)
    3 print(res)
    4 # <filter object at 0x00000291B3981470>
    5 print("英文人名有:",list(res))
    6 # 英文人名有: ['Allen', 'Leo']

    也可以处理其他的

    1 people = [
    2     {"name":"A","age":9000},
    3     {"name":"B","age":900},
    4     {"name":"C","age":18},
    5     {"name":"D","age":50}
    6 ]
    7 res = filter(lambda x: x["age"] < 100, people)
    8 print(list(res))
    9 # [{'name': 'C', 'age': 18}, {'name': 'D', 'age': 50}]

    reduce函数

    功能:把所有数据合并

    1 num = [1,2,3,100]
    2 def reduce_test(func,num):
    3     res = 1
    4     for i in num:
    5         res = func(i,res)
    6     return res
    7 res = reduce_test(lambda x,y: x * y, num)
    8 print(res)
    9 # 600

    指定一个倍数

     1 num = [1,2,3,100]
     2 def reduce_test(func,num,initial = None):
     3     if initial == None:
     4         res = 1
     5     else:
     6         res = initial
     7 
     8         for i in num:
     9             res = func(i,res)
    10         return res
    11 res = reduce_test(lambda x,y: x * y, num, 10)
    12 print(res)
    13 # 6000

    reduce函数

    1 from functools import reduce
    2 
    3 num = [1, 2, 3, 100]
    4 res = reduce(lambda x, y: x * y, num, 10)
    5 print(res)
    6 # 6000

    注意:map和reduce适合共同在大数据中使用

    内置函数

    abs() 绝对值

    all() 判断内部所有元素的布尔值为Ture则Ture,否则假  

    注意:如果可迭代对象是空的返回True

    any() 判断内部元素的布尔值有一个为Ture则Ture,否则假

    bin() 十进制转成二进制

    hex() 十进制转十六进制

    oct() 十进制转八进制

    bool() 求布尔值

    注意:None,空,0的布尔值为False

    bytes()转换成字节,需要指定编码 

    1 name = "你好"
    2 print(bytes(name,encoding = "utf-8"))
    3 # b'xe4xbdxa0xe5xa5xbd'

    .decode() 按指定编码方式解码 

    1 print(bytes(name,encoding = "utf-8").decode("utf-8"))
    2 # 你好

    dir() 打印某一对象的方法,但不解释

    help() 打印方法且详细解释

    divmod(a,b) a除b的商并取余 

    1 a = divmod(10,3)
    2 print(a)
    3 #(3, 1)

    eval() 把字符串中的数据结构提取出来、把字符串中的数学运算计算出来

    hash() 得出固定值,不能根据得到结果反推原数据,只要数据不变则得到结果不变

    hashable即不可变数据类型,unhashable即可变数据类型

     1 name = "aff"
     2 print("old_value:",hash(name))
     3 print(hash(name))
     4 print(hash(name))
     5 name = "s"
     6 print("new_value:",hash(name))
     7 # old_value: 9152753171858710842
     8 #            9152753171858710842
     9 #            9152753171858710842
    10 # new_value: -4828918846689666711

    isinstance() 判断是否是类型 

     1 print(isinstance(1,int))     
     2 print(isinstance(1.11,float))
     3 print(isinstance("1",int))
     4 print(isinstance("1",str))
     5 print(isinstance([],list))
     6 # True
     7 # True
     8 # False
     9 # True
    10 # True

    globals() 打印全局变量(包括系统提供的)

    locals() 打印局部变量 

    zip() 按照一一对应的关系生成一个个元组,两边长度不一致时从左到右取较短相同长度的元素

    1 print(zip(("a","b","c"),(1,2,3)))
    2 #<zip object at 0x00000289A9C7E148>
    3 print(list(zip(("a","b","c"),(1,2,3))))
    4 #[('a', 1), ('b', 2), ('c', 3)]
    5 print(list(zip(("a","b","c","d"),(1,2,3))))
    6 #[('a', 1), ('b', 2), ('c', 3)]
    7 print(list(zip(("a","b","c"),(1,2,3,4))))
    8 #[('a', 1), ('b', 2), ('c', 3)]

    只要传入的两个值都是有序列的即可

    1 p = {"name":"Jenny","age":18,"gender":"female"}
    2 print(list(zip(p.keys(),p.values())))
    3 #[('name', 'Jenny'), ('age', 18), ('gender', 'female')]
    4 print(list(zip("hello","1245435")))
    5 # [('h', '1'), ('e', '2'), ('l', '4'), ('l', '5'), ('o', '4')]

    max()取最大值      min()取最小值  

    对字典比较默认比key,从左到右一一比较

    1 l = {"A_age":18,'B_age':89,"C_age":50,"D_age":30}
    2 m_list = list(zip(l.values(),l.keys()))
    3 print(m_list)
    4 print(max(m_list))
    5 # [(18, 'A_age'), (89, 'B_age'), (50, 'C_age'), (30, 'D_age')]
    6 # (89, 'B_age')

    从元素的第一位往后比值,一旦有一位是最大的,后面不再比较

    1 d = {"a10","a8","a03"}
    2 print(max(d))
    3 #a8 第一位一样,比第二位,8>1>0,直接得出最大值,后面不比了

    可以指定比较逻辑

    1 ages = [
    2     {"name": "a", "age": 18},
    3     {"name": "b", "age": 50},
    4     {"name": "c", "age": 99}]
    5 print(max(ages, key=lambda dic: dic["age"]))
    6 # {'name': 'c', 'age': 99}

    sorted() 升序排序,用法与max()类似

    注意:排序本质就是比较大小,同类型之间才可以比较

    1 prices = {
    2     "a": 900,
    3     "b": 800,
    4     "c": 1000
    5 }
    6 print(sorted(prices, key=lambda key: prices[key]))
    7 # ['b', 'a', 'c']
    8 print(sorted(zip(prices.values(), prices.keys())))
    9 # [(800, 'b'), (900, 'a'), (1000, 'c')]

    ord() 打印出ASCII码字母代表的数字

    chr() 打印出ASCII码数字代表的字母 pow()

    1 print(chr(97))
    2 print(ord("a"))
    3 # a
    4 # 97

    pow()  

    pow(a,b) 求a^b

    pow(a,b,c) 求a^b%c

    reversed() 反转

    反转后没有保存

    round() 四舍五入

    set() 变成集合

    slice()切片

     主要为了提高程序的可读性,可以指定步长

    1 m = "hello"
    2 s = slice(3,5)
    3 print(m[s])
    4 #lo

    sum() 求和

    type() 查看数据类型

    vars() 如果没有参数,等于locals(),有参数则显示帮助

    import 导入模块

    1 import test #调用.py文件名
    2 test.hi()
    3 #HELLO
    4 z = __import__("test") #调用字符串名
    5 z.hi()
    6 #HELLO
  • 相关阅读:
    According to TLD or attribute directive in tag file, attribute end does not accept any expressions
    Several ports (8080, 8009) required by Tomcat v6.0 Server at localhost are already in use.
    sql注入漏洞
    Servlet—简单的管理系统
    ServletContext与网站计数器
    VS2010+ICE3.5运行官方demo报错----std::bad_alloc
    java 使用相对路径读取文件
    shell编程 if 注意事项
    Ubuntu12.04下eclipse提示框黑色背景色的修改方法
    解决Ubuntu环境变量错误导致无法正常登录
  • 原文地址:https://www.cnblogs.com/jennifer224/p/12367364.html
Copyright © 2020-2023  润新知