pyhton中实现switch代码
在php教程中有
switch ($value) {
case 'a':
$result = $x * 5;
break;
case 'b':
$result = $x + 7;
break;
case 'c':
$result = $x - 2;
break;
}
Python的等价实现为
choice = 'ham'
print {'spam': 1.25, # A dictionary-based 'switch'
'ham': 1.99, # Use has_key or get for default
'eggs': 0.99,
'bacon': 1.10}[choice]
看一个更详细的实例
def a(s):
print s
def switch(ch):
try:
{'1': lambda : a("one"),
'2': lambda : a("two"),
'3': lambda : a("three"),
'a': lambda : a("Letter a")
}[ch]()
except KeyError:
a("Key not Found")
eg:
>>switch('1')
one
>>switch('a')
Letter a
>>switch('b')
Key not Found
时间: 2024-09-20 19:36:28