Python3基础-高阶函数

 高阶函数  

  • 函数本身可以赋值给变量,赋值后变量为函数;
  • 允许将函数本身作为参数传入另一个函数;
  • 允许返回一个函数。
def add(x,y,f):
    return f(x) + f(y)
  
  
res = add(3,-6,abs)
print(res)<br>#abs()求绝对值

  

 几种常用的高阶函数 

map函数

  • 接收一个函数f和多个可迭代对象,依次取值作用在函数f
  • 返回对象
def fun(x,y,z):
    return x+y+z
r=map(fun,[1,2,3,4],[3,4,5,6],[4,5,6])
print(list(r))#返回的是客迭代对象 需用list转化

reduce函数

  • reduce(f, [x1, x2, x3, x4]) =f(f(f(x1,x2),x3),x4)
  • 在f中传入两个值往后循环作用
  • python3中通过导入模块使用  from functools import reduce
  • 返回值
def is_old(n):
    return n%2==1
reduce_vue=reduce(is_old,[1, 2, 4, 5, 6, 9, 10, 15])
print(reduce)

filter函数

  • 在函数f返回-1时,过滤掉该值
  • 返回对象
def is_old(n):
    return n%2==1#过滤掉偶数
filter_vue=filter(is_old,[1, 2, 4, 5, 6, 9, 10, 15])
print(list(filter_vue))#返回的是客迭代对象 需用list转化 

  

sorted函数

  • 可以直接对对象排序,返回一个列表对象
print(sorted(['Google', 'Runoob', 'Taobao', 'Baidu']))
print(sorted('653412'))
print(sorted({1:'q',3:'c',2:'g'}))#默认对键进行排序
print(sorted({1:'q',3:'c',2:'g'}.keys()))#对键进行排序
print(sorted({1:'q',3:'c',2:'g'}.values()))#对值进行排序

结果:
结果:
[8, 11, 14]
10
[1, 5, 9, 15]
['Baidu', 'Google', 'Runoob', 'Taobao']
['1', '2', '3', '4', '5', '6']
[1, 2, 3]
[1, 2, 3]
['c', 'g', 'q']
  • 通过其他声明进行排序,key接受一个函数,这个函数只接受一个元素,默认为None
print(sorted([36, 5, -12, 9, -21]))
print(sorted([36, 5, -12, 9, -21], key=abs))
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave','B', 10)]
print(sorted(students,key=lambda s:s[2])) #按照年龄来排序
结果:
[-21, -12, 5, 9, 36] [5, 9, -12, -21, 36] [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
  • 进行反向排序reverse = True 降序 , reverse = False 升序
print(sorted([36, 5, -12, 9, -21], key=abs,reverse=True))
结果
[36, -21, -12, 9, 5]
  •  实例 
要求1.正数在前负数在后 2.整数从小到大 3.负数从大到小
list1=[7, -8, 4, 5, 0, -2, -5]
def key_1(x):
    return x<0,abs(x)
print(sorted(list1,key=key_1))
结果:[0, 4, 5, 7, -2, -5, -8]


要求2.排序:小写-大写-奇数-偶数
s = 'asdf234GDSdsf23'  
print("".join(sorted(s, key=lambda x:(x.isdigit(),x.isupper(),x.isdigit() and int(x)%2==0))))
结果:asdfdsfGDS33242

 总结 

  • 在sorted函数使用时,如果key=None,则按照从小到大正常排序
  • 如果key中有一个条件,则按照key指定函数条件进行排序
  • 如果key中函数f返回-1(Flase),则对象考前排序,反之靠后排序
  • 如果key中有多个条件,则按照条件顺序做优先级

  

 

posted @ 2017-08-10 09:01  Ronny_bin  阅读(102)  评论(0)    收藏  举报