Python implements function calling methods with similar structures.
Python dict is easy to use. You can customize the key value and access it through subscript, for example:
Copy codeThe Code is as follows:
>>> D = {'key1': 'value1 ',
... 'Key2': 'value2 ',
... 'Key3': 'value3 '}
>>> Print d ['key2']
Value2
>>>
Lambda expressions are also very useful, for example:
Copy codeThe Code is as follows:
>>> F = lambda x: x ** 2
>>> Print f (2)
4
>>>
The combination of the two can implement function calls with similar structures, which is convenient to use. The example is as follows:
Example 1: Without Parameters
Copy codeThe Code is as follows:
#! /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 stopped'
Def doRestart ():
Print 'do restart'
If _ name _ = '_ main __':
While True:
Print msgCtrl
Export CTRL = raw_input ('input :')
If not ctrlMap. has_key (partition CTRL): break
CtrlMap [Export CTRL] ()
Example 2: With Parameters
Copy codeThe Code is as follows:
#! /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
Export CTRL = raw_input ('input :')
If not ctrlMap. has_key (partition CTRL): break
Print ctrlMap [Export CTRL] (), "\ n"