zoukankan      html  css  js  c++  java
  • python匿名函数lambda与switch的实现

    1,lambda的语法跟es6的箭头函数差不多

    >>> show=lambda x,y: x * y
    >>> show( 10, 20 )
    200

    2,递归求阶乘

    >>> def fab( n ):
    ...     if n == 0:
    ...             return 1
    ...     else:
    ...             return n * fab( n - 1)
    ... 
    >>> fab( 3 )
    6
    >>> fab( 5 )
    120
    >>> fab( 6 )
    720
    >>> 

    利用reduce函数,也可以实现累计运算

    >>> l = range( 1, 6 )
    >>> l
    [1, 2, 3, 4, 5]
    >>> def f( x, y ):
    ...     return x * y
    ... 
    >>> reduce( f, l )
    120
    >>> 

    不需要定义函数,可以用lambda表达式简化

    >>> fab = lambda x, y: x * y
    >>> reduce( fab, [ 1, 2, 3, 4, 5, 6 ] )
    720
    >>> reduce( lambda x,y: x *y, [ 1, 2, 3, 4, 5, 6 ] )
    720
    >>> 

    3,字典+函数可以实现switch的分支判断效果

    if。。。。else实现一个加减法

    #!/usr/bin/python
    #coding:utf-8
    
    from __future__ import division
    
    def add( a, b ):
        return a + b
    def sbb( a, b ):
        return a - b
    def mul( a, b ):
        return a * b
    def div( a, b ):
        return a / b
    
    
    def oper( x, o, y ):
        if o == '+':
            return add( x, y )
        elif o == '-':
            return sbb( x, y )
        elif o == '*':
            return mul( x, y )
        elif o == '/':
            return div( x, y )
        else:
            pass
    
    
    print oper( 10, '/', 20 )

    用字典和函数改造成switch的方式

    #!/usr/bin/python
    #coding:utf-8
    
    from __future__ import division
    
    def add( a, b ):
        return a + b
    def sbb( a, b ):
        return a - b
    def mul( a, b ):
        return a * b
    def div( a, b ):
        return a / b
    
    oper = { '+' : add, '-' : sbb, '*' : mul, '/' : div }
    def mySwitch( o, x, y ):
        #return oper[o]( x, y )
        #oper.get(o)等价于oper[0]取字典中的某一项
        return oper.get(o)( x, y )
    
    print mySwitch( '/', 10, 20 )
  • 相关阅读:
    python并发编程之多进程
    python并发编程之多进程理论部分
    Python GIL(Global Interpreter Lock)
    python并发编程之多线程
    前端基础之CSS
    前端知识之HTML内容
    Python杂货铺-(1)os模块在python中执行shell命令
    Hive学习小记-(17)inline(array(struct))与explode
    Hive学习小记-(16)hive加载解析json文件
    Hive学习小记-(15)transform函数
  • 原文地址:https://www.cnblogs.com/ghostwu/p/8604832.html
Copyright © 2011-2022 走看看