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 )

 

posted @ 2018-03-19 21:40  ghostwu  阅读(1101)  评论(0编辑  收藏  举报
Copyright ©2017 ghostwu