Python's dict is easy to use, and you can customize the key value and access it through the following example:
Copy CodeThe code is as follows:
>>> d = {' Key1 ': ' value1 ',
... ' Key2 ': ' value2 ',
... ' Key3 ': ' Value3 '}
>>> print d[' Key2 ']
value2
>>>
Lambda expressions are also useful, as shown in the following example:
Copy CodeThe code is as follows:
>>> f = Lambda x:x**2
>>> print F (2)
4
>>>
The combination of the two can implement similar function calls, which are convenient to use, as shown in the following example:
example one: without parameters
Copy the Code code 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 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] ()
Example two: with parameters
Copy the Code code 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
Cmdctrl = raw_input (' Input: ')
If not Ctrlmap.has_key (Cmdctrl): Break
Print Ctrlmap[cmdctrl] (10,2), "\ n"