Python3基础-函数式编程

1、高阶函数【函数式编程】

  • 函数的传入参数是一个函数名
  • 函数的返回值是一个函数名
  • 特性:
  1. #不可变数据:不用变量保存状态,不修改变量
    #非函数式
    a=1
    def inc_test1():
        global a
        a += 1  #赋值 ,修改变量
        return  a
    inc_test1()
    print(a)
    
    #函数式
    a = 1
    def inc_test1(n):
        return  n+1      #不修改变量
    print(inc_test1(2))
    print(a)
  2. #测试点:传入参数是一个函数名 test1
    def test(n): #n=test1
        print(n)
    
    def test1(name):
        print('my name is %s'%name)
    test(test1)  #将test1函数名作为实参传入
    
    """
    执行结果 
    <function test1 at 0x03979738>
    """
    
    #测试点:传入参数是一个函数名 test1()
    def test(n): #n=test1
        print(n)
    
    def test1(name):
        print('my name is %s'%name)
    test(test1('susu'))
    """
    执行结果
    my name is susu
    None
    """
    
    #测试点 返回值包含函数名称
    def test():
        print("测试函数式")
        return  test
    
    print(test())
    """
    执行结果
    测试函数式
    <function test at 0x013F9738>
    """
    
    #错误测试点 返回值包含函数名称
    # def test():
    #     print("测试函数式")
    #     return  test() #循环调用test()
    #
    # print(test())
    """
    执行结果
    RecursionError: maximum recursion depth exceeded while calling a Python object
    """
    
    #测试点 返回值包含函数名称
    def foo():
        print("my foo")
    
    def test():
        print("测试函数式")
        return  foo()
    
    print(test())
    """
    测试函数式
    my foo
    None
    """
  3. #在函数的最后一步调用另外一个函数(最后一行不一定是函数的最后一步)
    #函数test1在test内为尾调用
    def test1(n):
        return  n
    
    def test(x):
        return test1(x)
    
    
    #函数bar1和bar2在bar3内均为尾调用,二者在if判断条件不同的情况下都有可能作为函数的最后一步
    def bar1(n):
        return  n
    
    def bar2(n):
        return  n
    
    def bar3(x):
        if type(x) is str:
            return  bar1(x)
        elif type(x) is int:
            return  bar3(x)
    
    #函数test在test1内为非尾调用
    def test(n):
        return n
    
    def test1(x):
        y=test(x)
        return  y
    
    #函数test在test1内为非尾调用
    def test(n):
        return  n
    
    def test(x):
        return test1(x)+1
  • 优点:代码少
  • 缺点:可读性差

2、面向过程  

过程即解决问题的步骤,面向过程的设计就像设计好一条工业流水线,是一种机械式的思维方式

  1. 优点:程序结构清晰,可以把复杂的问题简单化,流程化。
  2. 缺点:可扩展性差,改动一个地方很可能要改多个地方,牵一发而动全身。
  3. 应用场景:linux内核,git,httpd,shell脚本.

3、高阶函数之map函数

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

#列表数值处理
#方法1
def add_one(x):
    return  x+1

def reduce_one(x):
    return  x-1

def square(x):
    return  x**2

def map_test(func,array):
    res_array=[]
    for value in array:
        res_value=func(value)
        res_array.append(res_value)
    return  res_array

array=[1,2,3,4,5,6]
test_array=map_test(square,array)
print(test_array)
test_array1=map_test(add_one,array)
print(test_array1)
test_array2=map_test(reduce_one,array)
print(test_array2)
"""
执行结果
[1, 4, 9, 16, 25, 36]
[2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5]
"""

#方法2-lambda
def map_test(func,array): #func=lambda x:x+1
    res_array=[]
    for value in array:
        res_value=func(value)
        res_array.append(res_value)

    return  res_array

array=[1,2,3,4,5,6]
test_array=map_test(lambda x:x+1,array)
print(test_array)
test_array1=map_test(lambda x:x-1,array)
print(test_array1)
test_array2=map_test(lambda x:x**2,array)
print(test_array2)
"""
执行结果
[2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5]
[1, 4, 9, 16, 25, 36]
"""

#方法3-map()
array=[1,2,3,4,5,6]
res = map(lambda x:x+1,array) #内置函数 map()函数   map函数==map_test函数
print("内置函数map,处理结果",res) #打印 迭代器
print(list(res))
print("传的是匿名函数,处理结果",list(map(lambda x:x**2,array)))
"""
执行结果
[2, 3, 4, 5, 6, 7]
传的是匿名函数,处理结果 [1, 4, 9, 16, 25, 36]
"""
print("传的是有名函数,处理结果",list(map(reduce_one,array))) #调用方法1的reduce_one的方法
"""
执行结果
传的是有名函数,处理结果 [0, 1, 2, 3, 4, 5]
"""

4、高阶函数之filter函数

filter遍历序列中的每个元素,判断每个元素得到布尔值;如果是True,则留下来

#判断列表中的元素是否不包含特定字符,则该元素加入到一个新的列表中去
#方法1

def filter_test(array):
    res = []
    for value in  array:
        if value.startswith('hz'):
            res.append(value)
    return  res

array=['hz_小林','hz_大林','Hz_小苏','hz_小夏','hz_小宋','苏苏']
print(filter_test(array))

"""
执行结果
['hz_小林', 'hz_大林', 'hz_小夏', 'hz_小宋']
"""

#方法二
def startswith_num(n):
    return n.startswith('hz')

def filter_test(func,array):
    res = []
    for value in array:
        if  func(value):
            res.append(value)
    return  res

array=['hz_小林','hz_大林','Hz_小苏','hz_小夏','hz_小宋','苏苏']
print(filter_test(startswith_num,array))
"""
执行结果
['hz_小林', 'hz_大林', 'hz_小夏', 'hz_小宋']
"""

#方法三 lambda 匿名函数
def filter_test(func,array):
    res = []
    for value in array:
        if  func(value):
            res.append(value)
    return  res
array=['hz_小林','hz_大林','Hz_小苏','hz_小夏','hz_小宋','苏苏']
print(filter_test(lambda x:x.startswith('hz'),array))
"""
执行结果
['hz_小林', 'hz_大林', 'hz_小夏', 'hz_小宋']
"""

#方法四 filter函数

array=['hz_小林','hz_大林','Hz_小苏','hz_小夏','hz_小宋','苏苏']
print(list(filter(lambda x:x.startswith('hz'),array)))
"""
执行结果
['hz_小林', 'hz_大林', 'hz_小夏', 'hz_小宋']
"""

5、高阶函数之reduce函数 

处理一个序列,然后把序列进行合并操作

#将列表中的每个元素相乘
def reduce_num(x,y):
    return  x*y

def reduce_test(func,array,init=None):
    if init == None:
        sum_s = array.pop(0)
    else:
        sum_s=init
    for value in array:
        sum_s =func(sum_s,value)
    return  sum_s

array=[1,2,3,4,5,6,7]
print(reduce_test(reduce_num,array))

from functools import reduce

print(reduce(reduce_num,array))
print(reduce(lambda x,y:x*y,array))
"""
执行结果
5040
5040
5040
"""

猜你喜欢

转载自www.cnblogs.com/sugh/p/11687794.html