[Python] 函数,,高阶函数接受函数为参
[Python] 函数,,高阶函数接受函数为参
高阶函数
接受函数为参数,或者把函数作为结果返回的函数View CodeView Code嵌套函数
封装内部函数提高效率,比如阶乘函数先检查输入数据闭包(closure)
外部函数返回一个函数1 def nth_power(exponent): 2 def exponent_of(base): 3 return base ** exponent 4 return exponent_of 5 6 square = nth_power(2) 7 cube = nth_power(3) 8 9 print(square(2))10 print(cube(3))View Code
匿名函数
只有一行是表达式而不是语句传入的参数是一个可迭代对象,lambda内部调用可迭代对象的__next__方法取值当做参数传入lambda函数冒号前面的值,然后返回冒号后表达式计算的结果优点:减少代码的重复性;模块化代码1 [(lambda x:x*x)(x) for x in range(10)]View Code
1 l = [(1,20),(3,0),(9,10),(2,-1)]2 l.sort(key=lambda x:x[1])3 print(l)View Code
可调用对象
():可调用运算符可调用对象实现了内置函数callabel()1 import random 2 3 class BingoCage: 4 def __init__(self, items): 5 self._items = list(items) 6 random.shuffle(self._items) 7 def pick(self): 8 try: 9 return self._items.pop()10 except IndexError:11 raise LookupError(‘pick from empty BingoCage‘)12 def __call__(self):13 return self.pick()14 15 bingo = BingoCage(range(5))16 bingo.pick()View Code
函数式编程
代码中每一块都是不可变的,即由纯函数的形式组成map(function,iterable):对于iterable中的每个元素,都运用function函数,最后返回一个新的可遍历集合filter(function,iterable):对于iterable中的每个元素,都运用function函数进行判断,将返回True的元素组成一个新的可遍历集合reduce(function,iterable):对一个集合中前两个元素进行运算,返回的结果再和第三个元素运算,依次类推1 # map函数2 def factorial(n):3 return 1 if n < 2 else n * factorial(n-1)4 5 fact = factorial6 list(map(fact,range(10)))View Code
1 list(map(fact, filter(lambda n:n%2,range(6))))View Code
1 from functools import reduce 2 reduce(lambda x, y: x+y, [1,2,3,4,5])View Code
[Python] 函数
评论关闭