我试图在python上使用字典作为switch case,但是,参数似乎没有传递给被调用的函数,请帮助:
def switchcase(num,cc):
def fa(num):
out= num*1.1;
def fb(num):
out= num*2.2;
def fc(num):
out= num*3.3;
def fd(num):
out= num*4.4;
options = {
"a":fa(num),
"b":fb(num),
"c":fc(num),
"d":fd(num)
}
out=0
options[cc];
return out
print switchcase(10,"a")
输出为0,我无法弄清楚问题
答案 0 :(得分:6)
问题是:
out=0
options[cc];
return out
基本上 - 无论options[cc]
给你什么,你都会返回0
,因为它是out
的价值。请注意,在各种out
,fa
,...函数中设置fb
不会更改调用者中out
的值。< / p>
你可能想要:
def switchcase(num,cc):
def fa(num):
return num*1.1;
def fb(num):
return num*2.2;
def fc(num):
return num*3.3;
def fd(num):
return num*4.4;
options = {
"a":fa(num),
"b":fb(num),
"c":fc(num),
"d":fd(num)
}
return options[cc];
另请注意,这在实践中会非常低效。每次拨打switchcase
时,您都会创建4个功能(并呼叫每个功能)。
我猜你真的想要创建一个预先制作的功能图。然后,您可以从地图中选择您真正想要的功能,并使用给定的数字调用它:
def fa(num):
return num*1.1
def fb(num):
return num*2.2
def fc(num):
return num*3.3
def fd(num):
return num*4.4
OPTIONS = {
"a":fa,
"b":fb,
"c":fc,
"d":fd
}
def switchcase(num,cc):
return OPTIONS[cc](num)
答案 1 :(得分:0)
这是另一种选择。您可以导航到切换台外部的必要方法,并在需要时传递可选参数:
def fa(num):
return num*1.1
def fb(num):
return num*2.2
def fc(num):
return num*3.3
def fd(num, option=1):
return num*4.4*option
def f_default(num):
return num
def switchcase(cc):
return {
"a":fa,
"b":fb,
"c":fc,
"d":fd,
}.get(cc, f_default)
print switchcase("a")(10) # for Python 3 --> print(switchcase("a")(10))
print switchcase("d")(10, 3) # for Python 3 --> print(switchcase("d")(10, 3))
打印(switchcase( “A”)(10))
11.0
打印(switchcase(“d”)(10,3))
132.0
打印(switchcase( “DDD”)(10))
10
答案 2 :(得分:0)
另一个较短的版本是:
def switchcase(num, cc):
return {
"a": lambda: num * 1.1,
"b": lambda: num * 2.2,
"c": lambda: num * 3.3,
"d": lambda: num * 4.4,
}.get(cc, lambda: None)()
print (switchcase(10,"a"))