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 )
  • 相关阅读:
    HTTP协议入门
    TCP/IP的分层管理
    TCP与UDP
    如何处理某个Web页面的HTTP请求
    AGC005D ~K Perm Counting
    “玲珑杯” 线上赛Round #17 B 震惊,99%+的中国人都会算错的问题
    bzoj4455 [Zjoi2016]小星星
    AGC010F Tree Game
    AGC016E Poor Turkeys
    AGC003E Sequential operations on Sequence
  • 原文地址:https://www.cnblogs.com/ghostwu/p/8604832.html
Copyright © 2011-2022 走看看