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/pythonmsgCtrl = "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/pythonmsgCtrl = "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"