zoukankan      html  css  js  c++  java
  • python之函数filter、reduce

    ---恢复内容开始---

    一、filter函数

    filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。

    该接收两个参数,第一个为函数,第二个为序列,对序列中每个元素进行for循环,然后将每个元素传递给第一个位置的函数,然后返回 True 或 False,最后将返回 True 的元素放到新列表中

    1、使用for循环将前面包含sb的文本过滤出来,

    moive_people = ['sb_alex','sb_wupeiqi','yuanhao','sb_lihaifeng']
    
    def filter_test(array):
        ret = []
        for p in array:
             if  not p.startswith("sb"):
                 ret.append(p)
         return ret
     print(filter_test(moive_people))  #['yuanhao']

    2、将后面包含sb的文本过滤出来,如果还按照上面的方法写就显得很麻烦,而且代码重复,可以将for循环的主体部分使用函数定义独立出来,方便后续进行代码维护

     1 moive_people = ['alex_sb','sb_wupeiqi_sb','yuanhao','sb_lihaifeng_sb']
     2 def sb_show(n):
     3     return n.endswith('sb')
     4 def filter_test(func,array):
     5     ret = []
     6     for p in array:
     7         if  not func(p):
     8             ret.append(p)
     9     return ret
    10 print(filter_test(sb_show,moive_people)) #['yuanhao']

    备注:在上面的代码中,我将p.endswith()预先定义函数,然后后续直接调用函数,如果还有变化,只需要使用函数定义出来,然后直接调用;

    3、对2的函数进行优化,将预先定义的sb_show函数使用lambda匿名函数进行替换,减少代码数量

    1 def filter_test(func,array):
    2     ret = []
    3     for p in array:
    4         if  not func(p):
    5             ret.append(p)
    6     return ret
    7 print(filter_test(lambda n:n.endswith('sb'),moive_people))

    4、filter函数

    1 moive_people = ['alex_sb','sb_wupeiqi_sb','yuanhao','sb_lihaifeng_sb']
    2 #下面的结果是一个内存地址,如果要获取值,需要进行list
    3 #<filter object at 0x0000026CB0A4FAC8>
    4 print(filter(lambda n:n.endswith('sb'),moive_people))
    5 #['alex_sb', 'sb_wupeiqi_sb', 'sb_lihaifeng_sb']
    6 print(list(filter(lambda n:n.endswith('sb'),moive_people)))
    7 #['alex_sb', 'sb_wupeiqi_sb', 'sb_lihaifeng_sb']
    8 res=  filter(lambda n:n.endswith('sb'),moive_people)
    9 print(list(res))

     二、reduce函数

    reduce() 函数会对参数序列中元素进行累积。

    函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果

    1、采用for循环的方法进行实现

    1 num1 = range(1,101)
    2 res= 0
    3 for i  in num1:
    4     res = res+i
    5 
    6 print(res) #5050

    2、使用函数的方式进行实现

    1 num1 = range(1,101)
    2 def reduce_test(array):
    3 
    4     res= 0
    5     for i  in array:
    6         res = res+i
    7     return(res)
    8 print(reduce_test(num1)) #5050

    3、对序列中的每个元素进行乘积

    1 num1 = range(1,6)
    2 def mul(x,y):
    3     return x*y
    4 def reduce_test(func,array):
    5     res =1
    6     for i in array:
    7         res = func(res,i)
    8     return res
    9 print(reduce_test(mul,num1))

    4、对3函数进行优化

    1 def reduce_test(func,array):
    2     res =1
    3     for i in array:
    4         res = func(res,i)
    5     return res
    6 print(reduce_test(lambda x,y:x*y,num1))

    5、对4函数进行优化,对函数增加一个默认参数

     1 num1 = [1,2,3,4,5,6]
     2 # def mul(x,y):
     3 #     return x*y
     4 def reduce_test(func,array,init=None):
     5     if init is None:
     6         res = array.pop(0)
     7     else:
     8         res= init
     9     for i in array:
    10         print(i)
    11         res = func(res,i)
    12     return res
    13 print(reduce_test(lambda x,y:x*y,num1,100))

    6、reduce函数

    1 from functools import reduce
    2 num1 = [1,2,3,4,5,6]
    3 
    4 print(reduce(lambda x,y:x+y,num1,1)) #22
    5 print(reduce(lambda x,y:x*y,num1,10)) #7200
    6 print(reduce(lambda x,y:x/y,num1,100)) #0.1388888888888889

    三、map函数

    对序列中元素进行for循环,然后对每个元素进行逻辑处理

    1、对列表中的元素进行平方处理

    1 num1 = [1,2,3,4,5,6]
    2 ret= []
    3 for i in num1:
    4     ret.append(i**2)
    5 print(ret)

    2、对列表中的元素进行自增加1处理

    1 num1 = [1,2,3,4,5,6]
    2 ret= []
    3 for i in num1:
    4     ret.append(i+1)
    5 print(ret)

    3、使用函数方式进行处理

    1 num1 = [1,2,3,4,5,6]
    2 def map_test(array):
    3     res =[]
    4     for i in array:
    5         res.append(i+1)
    6     return res
    7 print(map_test(num1))  #[2, 3, 4, 5, 6, 7]

    4、对3函数进行优化,将for循环的主体代码部分预先使用函数进行定义

    1 num1 = [1,2,3,4,5,6]
    2 def reduce_one(x):
    3     return x+1
    4 def map_test(func,array):
    5     res =[]
    6     for i in array:
    7        res.append(func(i))
    8     return res
    9 print(map_test(reduce_one,num1)) #[2, 3, 4, 5, 6, 7]

    如果需求有其他变化,只需要对将函数定义出来,然后进行调用就可以了

    5、对4函数进行优化,使用lambda函数进行代替

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

    6、map函数

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

    ---恢复内容结束---

    一、filter函数

    filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。

    该接收两个参数,第一个为函数,第二个为序列,对序列中每个元素进行for循环,然后将每个元素传递给第一个位置的函数,然后返回 True 或 False,最后将返回 True 的元素放到新列表中

    1、使用for循环将前面包含sb的文本过滤出来,

    moive_people = ['sb_alex','sb_wupeiqi','yuanhao','sb_lihaifeng']
    
    def filter_test(array):
        ret = []
        for p in array:
             if  not p.startswith("sb"):
                 ret.append(p)
         return ret
     print(filter_test(moive_people))  #['yuanhao']

    2、将后面包含sb的文本过滤出来,如果还按照上面的方法写就显得很麻烦,而且代码重复,可以将for循环的主体部分使用函数定义独立出来,方便后续进行代码维护

     1 moive_people = ['alex_sb','sb_wupeiqi_sb','yuanhao','sb_lihaifeng_sb']
     2 def sb_show(n):
     3     return n.endswith('sb')
     4 def filter_test(func,array):
     5     ret = []
     6     for p in array:
     7         if  not func(p):
     8             ret.append(p)
     9     return ret
    10 print(filter_test(sb_show,moive_people)) #['yuanhao']

    备注:在上面的代码中,我将p.endswith()预先定义函数,然后后续直接调用函数,如果还有变化,只需要使用函数定义出来,然后直接调用;

    3、对2的函数进行优化,将预先定义的sb_show函数使用lambda匿名函数进行替换,减少代码数量

    1 def filter_test(func,array):
    2     ret = []
    3     for p in array:
    4         if  not func(p):
    5             ret.append(p)
    6     return ret
    7 print(filter_test(lambda n:n.endswith('sb'),moive_people))

    4、filter函数

    1 moive_people = ['alex_sb','sb_wupeiqi_sb','yuanhao','sb_lihaifeng_sb']
    2 #下面的结果是一个内存地址,如果要获取值,需要进行list
    3 #<filter object at 0x0000026CB0A4FAC8>
    4 print(filter(lambda n:n.endswith('sb'),moive_people))
    5 #['alex_sb', 'sb_wupeiqi_sb', 'sb_lihaifeng_sb']
    6 print(list(filter(lambda n:n.endswith('sb'),moive_people)))
    7 #['alex_sb', 'sb_wupeiqi_sb', 'sb_lihaifeng_sb']
    8 res=  filter(lambda n:n.endswith('sb'),moive_people)
    9 print(list(res))

     二、reduce函数

    reduce() 函数会对参数序列中元素进行累积。

    函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果

    1、采用for循环的方法进行实现

    1 num1 = range(1,101)
    2 res= 0
    3 for i  in num1:
    4     res = res+i
    5 
    6 print(res) #5050

    2、使用函数的方式进行实现

    1 num1 = range(1,101)
    2 def reduce_test(array):
    3 
    4     res= 0
    5     for i  in array:
    6         res = res+i
    7     return(res)
    8 print(reduce_test(num1)) #5050

    3、对序列中的每个元素进行乘积

    1 num1 = range(1,6)
    2 def mul(x,y):
    3     return x*y
    4 def reduce_test(func,array):
    5     res =1
    6     for i in array:
    7         res = func(res,i)
    8     return res
    9 print(reduce_test(mul,num1))

    4、对3函数进行优化

    1 def reduce_test(func,array):
    2     res =1
    3     for i in array:
    4         res = func(res,i)
    5     return res
    6 print(reduce_test(lambda x,y:x*y,num1))

    5、对4函数进行优化,对函数增加一个默认参数

     1 num1 = [1,2,3,4,5,6]
     2 # def mul(x,y):
     3 #     return x*y
     4 def reduce_test(func,array,init=None):
     5     if init is None:
     6         res = array.pop(0)
     7     else:
     8         res= init
     9     for i in array:
    10         print(i)
    11         res = func(res,i)
    12     return res
    13 print(reduce_test(lambda x,y:x*y,num1,100))

    6、reduce函数

    1 from functools import reduce
    2 num1 = [1,2,3,4,5,6]
    3 
    4 print(reduce(lambda x,y:x+y,num1,1)) #22
    5 print(reduce(lambda x,y:x*y,num1,10)) #7200
    6 print(reduce(lambda x,y:x/y,num1,100)) #0.1388888888888889

    三、map函数

    对序列中元素进行for循环,然后对每个元素进行逻辑处理

    1、对列表中的元素进行平方处理

    1 num1 = [1,2,3,4,5,6]
    2 ret= []
    3 for i in num1:
    4     ret.append(i**2)
    5 print(ret)

    2、对列表中的元素进行自增加1处理

    1 num1 = [1,2,3,4,5,6]
    2 ret= []
    3 for i in num1:
    4     ret.append(i+1)
    5 print(ret)

    3、使用函数方式进行处理

    1 num1 = [1,2,3,4,5,6]
    2 def map_test(array):
    3     res =[]
    4     for i in array:
    5         res.append(i+1)
    6     return res
    7 print(map_test(num1))  #[2, 3, 4, 5, 6, 7]

    4、对3函数进行优化,将for循环的主体代码部分预先使用函数进行定义

    1 num1 = [1,2,3,4,5,6]
    2 def reduce_one(x):
    3     return x+1
    4 def map_test(func,array):
    5     res =[]
    6     for i in array:
    7        res.append(func(i))
    8     return res
    9 print(map_test(reduce_one,num1)) #[2, 3, 4, 5, 6, 7]

    如果需求有其他变化,只需要对将函数定义出来,然后进行调用就可以了

    5、对4函数进行优化,使用lambda函数进行代替

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

    6、map函数

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

     四、其他内置函数

    1、zip函数

    zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

    如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。zip函数的作用类似于拉链

     1 print(list(zip(('张三'),(1,2))))#[('张', 1), ('三', 2)]
     2 print(zip(('张三'),(1,2))) #<zip object at 0x00000230F8D54B88>
     3 #[('M', 1), ('y', 2), (' ', 3)]
     4 print(list(zip(('My name is zhangsan'),(1,2,3))))
     5 print(list(zip(('My'),(1,2,3,4)))) #[('M', 1), ('y', 2)]
     6 
     7 ###使用zip函数将字典中的key与value值一一对应
     8 p = {'name':'alex','age':18,'gender':'none'}
     9 print(p.keys()) #dict_keys(['name', 'age', 'gender'])
    10 print(p.values()) #dict_values(['alex', 18, 'none'])
    11 print(list(p.keys())) #['name', 'age', 'gender']
    12 print(list(p.values())) #['alex', 18, 'none']
    13 #[('name', 'alex'), ('age', 18), ('gender', 'none')]
    14 print(list(zip(p.keys(),p.values())))
    15 print(zip(p.keys(),p.values())) #<zip object at 0x0000027B47A84F48>

    2、max、min函数

    备注:

    a、max函数处理的是可迭代对象,相当于for循环取出每个元素进行比较,注意,不同类型之间不能进行比较;

    b、每个元素之间比较,是从每个元素的第一个位置比较,如果这个位置分出大小,后面都不需要比较,直接得出这两个元素的大小;

    (1)、单纯数字的比较

    1 l3 = [12,34,130,-1,44]
    2 print(max(l3)) #130
    3 print(min(l3))#-1

    (2)、字典的比较

    1 age_dict = {'age1':18,'age3':30,'age4':87}
    2 #求出年龄最大的
    3 print(max(age_dict.values())) #87
    4 #默认比较key值
    5 print(max(age_dict))
    6 #求出年龄最大的keys与values
    7 
    8 print(list(max(zip(age_dict.values(),age_dict.keys()))))  #[87, 'age4']
     1 l = [
     2     (1,'a'),
     3     (2,'b'),
     4     (3,'e'),
     5     (5,'f')
     6 ]
     7 print(max(l))
     8 
     9 
    10 l1 = ['a10','b13','d13']
    11 print(list(max(l1))) #['d', '1', '3']
    12 
    13 # l2 = ['a10','b13','d13',10]
    14 # #TypeError: '>' not supported between instances of 'int' and 'str'
    15 # print(list(max(l2)))

    3、chr、ord函数

    1 # print(chr(97)) #a,chr的作用是将数字在ascii码表中的值显示出来
    2 # print(ord('c'))  #99
    3 # print(chr(33)) #! ascii码表中的33对应的值为'!'

    4、pow函数

    1 print(pow(2,3))  #2**3
    2 print(pow(2,3,2)) #2**3%2

    5、reversed 反转

    6、round四舍五入

    7、set()转换为集合

    8、slice() 切片

    1 l = 'hello'
    2 print(l[2:5])
    3 s= slice(3,5)
    4 s1 = slice(1,4,2)
    5 print(s)

    9、sorted 排序

    10、str

    11、type

    12、vars

    13、__imprort__

    14、eval

    ###将字符串中的结构给提取出来
    str_1 = "1+2*(5-1)-20/5"
    print(eval(str_1))
    str_2 = "{'k1':'1234','k2':'张三'}"
    print(eval(str_2))

    15、hash

    可hash的数据类型即为不可变数据类型,不可hash的数据类型即可变数据类型;

    hash是一种算法、算法结构;

    hash特性:

    不管传入的参数多大,计算的hash值长度是不变的;

    不能根据hash值去反推原参数;

    变量不变hash值不变;

    name = "zhangsan"
    print(hash(name)) #-6633503532806232964
    print(hash(name)) #-6633503532806232964
    print(hash(name)) #-6633503532806232964
    name = "张三"
    print(hash(name)) #247632540932985384

    16、bytes

    17、encoding、decode

    18、divmod

    19、bin、hex、oct

    print(bin(32)) #十进制转二进制
    print(hex(32)) #十进制转16进制
    print(oct(32)) #十进制转8进制
    """
    输出结果
    0b100000
    0x20
    0o40
    """
    

    20、globals、local

    
    
  • 相关阅读:
    内置函数二
    通信的几个程序
    TCP协议和UDP协议
    异常处理
    logging模块
    网络编程一些概念
    hashlib
    序列化模块
    time,sys,os模块
    random模块
  • 原文地址:https://www.cnblogs.com/tengjiang/p/9424783.html
Copyright © 2011-2022 走看看