zoukankan      html  css  js  c++  java
  • [Python] 函数

    高阶函数

    • 接受函数为参数,或者把函数作为结果返回的函数
    View Code

    View 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 = factorial
    6 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

  • 相关阅读:
    用C++读写EXCEL文件的几种方式比较
    20个值得收藏的网页设计开放课件
    char* 应用, 去除字符串内多余空格, 用算法而非库函数
    东拉西扯:王建硕主义
    Lisp 的本质(The Nature of Lisp)
    web前端:html
    [原译]理解并实现原型模式实现ICloneable接口.理解深浅拷贝
    [原译]理解并实现装饰器模式
    3分钟理解Lambda表达式
    [原译]实现IEnumerable接口&理解yield关键字
  • 原文地址:https://www.cnblogs.com/cxc1357/p/12708173.html
Copyright © 2011-2022 走看看