python常用高阶函数简介

# -*- coding: utf-8 -*-

#python 常用高阶函数



def fac(n):
    '''return n! zw'''
    return 1 if n <2 else n*fac(n-1)


print(fac.__doc__)


fa=fac

a=list(map(fa,range(5)))
# map 函数把每个元素都放到fa这个函数里面执行,并且是一个迭代器,就算外面必须用list才能显示出来
print('this is origin a:',a)
b=sorted(a,reverse=True)
# sorted 把a的排序后的结果复制给b 但是并没有改变a
print('this is a using sorted ',b)
print('this is a by using sorted :',a)


c=list.sort(a,reverse=True)

#list.sort只改变a的排序值 并不会把值返回给c 
print('this is c',c)
print('this is a by using list sort',a)



#sort 可以对字符长度排序


fruit =['b','dbc','eb','abcdef','gbcd']
sorted_fruit =sorted(fruit)
print('默认字符按照字母顺序排序:',sorted_fruit)


sorted_len_fruit =sorted(fruit,key=len)

print('按照字符的长度排序',sorted_len_fruit)



compound = list(map(fa,filter(lambda n:n%3,range(6))))

print('多个高阶函数的混用:',compound)

输出结果如下  
return n! zw
this is origin a: [1, 1, 2, 6, 24]
this is a using sorted  [24, 6, 2, 1, 1]
this is a by using sorted : [1, 1, 2, 6, 24]
this is c None
this is a by using list sort [24, 6, 2, 1, 1]
默认字符按照字母顺序排序: ['abcdef', 'b', 'dbc', 'eb', 'gbcd']
按照字符的长度排序 ['b', 'eb', 'dbc', 'gbcd', 'abcdef']
多个高阶函数的混用: [1, 2, 24, 120]

Process finished with exit code 0

你可能感兴趣的:(python,基础学习)