Python中实现结构相似的函数调用方法

yipeiwu_com6年前Python基础

python的dict用起来很方便,可以自定义key值,并通过下标访问,示例如下:

复制代码 代码如下:

>>> d = {'key1':'value1',
... 'key2':'value2',
... 'key3':'value3'}
>>> print d['key2']
value2
>>>

lambda表达式也是很实用的东东,示例如下:
复制代码 代码如下:

>>> f = lambda x : x**2
>>> print f(2)
4
>>>

两者结合可以实现结构相似的函数调用,使用起来很方便,示例如下:

示例一:不带参数 

复制代码 代码如下:

#! /usr/bin/python
 
msgCtrl = "1 : pause\n2 : stop\n3 : restart\nother to quit\n"
 
ctrlMap = {
'1':    lambda : doPause(),
'2':    lambda : doStop(),
'3':    lambda : doRestart()}
 
def doPause():
        print 'do pause'
 
def doStop():
        print 'do stop'
 
def doRestart():
        print 'do restart'
 
if __name__ == '__main__':
        while True:
                print msgCtrl
                cmdCtrl = raw_input('Input : ')
                if not ctrlMap.has_key(cmdCtrl):break
                ctrlMap[cmdCtrl]()

示例二:带参数

复制代码 代码如下:

#! /usr/bin/python
 
msgCtrl = "1 : +\n2 : -\n3 : *\nother to quit\n"
 
ctrlMap = {
'1':    lambda x,y : x+y,
'2':    lambda x,y : x-y,
'3':    lambda x,y : x*y}
 
 
if __name__ == '__main__':
        while True:
                print msgCtrl
                cmdCtrl = raw_input('Input : ')
                if not ctrlMap.has_key(cmdCtrl):break
                print ctrlMap[cmdCtrl](10,2),"\n"

相关文章

pandas中apply和transform方法的性能比较及区别介绍

pandas中apply和transform方法的性能比较及区别介绍

1. apply与transform 首先讲一下apply() 与transform()的相同点与不同点 相同点: 都能针对dataframe完成特征的计算,并且常常与groupby()...

Python模拟登录12306的方法

本文实例讲述了Python模拟登录12306的方法。分享给大家供大家参考。 具体实现方法如下: 复制代码 代码如下: #!/usr/bin/python # -*- coding: ut...

python使用生成器实现可迭代对象

本文实例为大家分享了python使用生成器实现可迭代对象的具体代码,供大家参考,具体内容如下 案例分析:       &nbs...

Python数据可视化:顶级绘图库plotly详解

Python数据可视化:顶级绘图库plotly详解

有史以来最牛逼的绘图工具,没有之一 plotly是现代平台的敏捷商业智能和数据科学库,它作为一款开源的绘图库,可以应用于Python、R、MATLAB、Excel、JavaScript...

python executemany的使用及注意事项

使用executemany对数据进行批量插入的话,要注意一下事项: #coding:utf8 conn = MySQLdb.connect(host = “localhost”, u...