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 )
  • 相关阅读:
    记一道乘法&加法线段树(模版题)
    2021CCPC网络赛(重赛)题解
    Codeforces Round #747 (Div. 2)题解
    F. Mattress Run 题解
    Codeforces Round #744 (Div. 3) G题题解
    AtCoder Beginner Contest 220部分题(G,H)题解
    Educational Codeforces Round 114 (Rated for Div. 2)题解
    Codeforces Global Round 16题解
    Educational Codeforces Round 113 (Rated for Div. 2)题解
    AtCoder Beginner Contest 182 F
  • 原文地址:https://www.cnblogs.com/ghostwu/p/8604832.html
Copyright © 2011-2022 走看看