Python3学习笔记:普通函数到高阶函数(参数为函数类型)——构建降序排列函数

'''

高阶函数:

1.接受一个或者多个函数作为参数(本次讨论类型)

2.返回一个函数

'''

lst = [2, 4, 6, 4, 2, 2, 8, 3]  #定义一个列表
'''

#1.普通函数
def sort(lst):
    newlist = []
    for x in lst:
        for i, y in enumerate(newlist):
            if x > y:
                newlist.insert(i, x)
                break
        else:
            newlist.append(x)

    return newlist

print(sort(lst))
'''
'''

#2.运用标记改造函数
def sort(lst, asc = False):
    newlist = []
    for x in lst:
        for i, y in enumerate(newlist):
            flag = x < y if asc else x > y
            if flag:
                newlist.insert(i, x)
                break
        else:
            newlist.append(x)

    return newlist
  
print(sort(lst))             #sort(lst)默认第二个参数为False(降序), 当为True时为升序。
'''
'''

#3.定义函数调用
def sort(lst, asc = False):
    def compare(a, b):      #定义一个比较函数
        return a < b if asc else a > b
    
    newlist = []
    for x in lst:
        for i, y in enumerate(newlist):
            if compare(x, y):    #调用函数
                newlist.insert(i, x)
                break
        else:
            newlist.append(x)

    return newlist

print(sort(lst))          #sort(lst)默认第二个参数为False(降序), 当为True时为升序。
'''
'''

#4.定义的函数放置在外
def compare(a, b) ->bool:
        return a > b       
#返回bool值
    
def sort(lst):
    
    newlist = []
    for x in lst:
        for i, y in enumerate(newlist):
            if compare(x, y):
                newlist.insert(i, x)
                break
        else:
            newlist.append(x)

    return newlist

print(sort(lst))
'''

'''

#5.调用函数作为参数
def compare(a, b) ->bool:
        return a > b
    
def sort(lst, fn):
    
    newlist = []
    for x in lst:
        for i, y in enumerate(newlist):
            if fn(x, y):
                newlist.insert(i, x)
                break
        else:
            newlist.append(x)

    return newlist

print(sort(lst, compare))        #compare函数作为参数传入
'''
'''

#6.函数封装为高阶函数
def sort(lst, fn = lambda a,b : a>b):
    
    newlist = []
    for x in lst:
        for i, y in enumerate(newlist):
            if fn(x, y):
                newlist.insert(i, x)
                break
        else:
            newlist.append(x)

    return newlist

print(sort(lst))
'''

你可能感兴趣的:(Python3学习笔记)