在 Python 中使用字典作为 switch 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21962763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using a dictionary as a switch statement in Python
提问by user3342163
I'm trying to make a simple calculator in Python, using a dictionary. Here's my code:
我正在尝试使用字典在 Python 中制作一个简单的计算器。这是我的代码:
def default():
print "Incorrect input!"
def add(a, b):
print a+b
def sub(a, b):
print a-b
def mult(a, b):
print a*b
def div(a, b):
print a/b
line = raw_input("Input: ")
parts = line.split(" ")
part1 = float(parts[0])
op = parts[1];
part3 = float(parts[2])
dict = {
'+': add(part1, part3),
'-': sub(part1, part3),
'*': mult(part1, part3),
'/': div(part1, part3)
}
try:
dict[op]
except KeyError:
default()
but all the functions are activated. What's the problem?
但是所有的功能都被激活了。有什么问题?
回答by Christian
Define your dictionary like pairs of the form str : function:
像以下形式的对一样定义您的字典str : function:
my_dict = {'+' : add,
'-' : sub,
'*' : mult,
'/' : div}
And then if you want to call an operation, use my_dict[op]to get a function, and then pass call it with the corresponding parameters:
然后如果你想调用一个操作,使用my_dict[op]来获取一个函数,然后通过相应的参数传递调用它:
my_dict[op] (part1, part3)
|___________|
|
function (parameters)
Note:Don't use Python built-in names as names of variables, or you will hide its implementation. Use my_dictinstead of dictfor example.
注意:不要使用 Python 内置名称作为变量的名称,否则您将隐藏其实现。使用my_dict代替dict例如。
回答by zmo
It is because when the dictionary is populated, it executes each operation with the operands,
and at the end, you're calling dict[op]which contains Noneand do nothing with it.
这是因为当字典被填充时,它会用操作数执行每个操作,最后,你调用dict[op]which 包含None它并且什么都不做。
What happens is:
发生的事情是:
# N.B.: in case this is not clear enough,
# what follows is the *BAD* code from the OP
# with inline explainations why this code is wrong
dict = {
# executes the function add, outputs the result and assign None to the key '+'
'+': add(part1, part3),
# executes the function sub, outputs the result and assign None to the key '-'
'-': sub(part1, part3),
# executes the function mult, outputs the result and assign None to the key '*'
'*': mult(part1, part3),
# executes the function div, outputs the result and assign None to the key '/'
'/': div(part1, part3)
}
try:
# gets the value at the key "op" and do nothing with it
dict[op]
except KeyError:
default()
which is why you get all outputs, and nothing happens in your tryblock.
这就是为什么您获得所有输出,而您的try块中没有任何反应。
You may want to actually do:
您可能想要实际执行以下操作:
dict = {
'+': add,
'-': sub,
'*': mult,
'/': div
}
try:
dict[op](part1, part3)
except KeyError:
default()
but as @christian wisely suggests, you should not use python reserved names as variable names, that could lead you into troubles. And another improvement I advice you todo is to print the result once, and make the functions lambdas:
但正如@christian 明智地建议的那样,您不应该使用 python 保留名称作为变量名,这可能会给您带来麻烦。我建议你做的另一个改进是打印一次结果,并使函数 lambdas:
d = {
'+': lambda x,y: x+y,
'-': lambda x,y: x-y,
'*': lambda x,y: x*y,
'/': lambda x,y: x/y
}
try:
print(d[op](part1, part3))
except KeyError:
default()
which will return the result and print it
这将返回结果并打印它

