我正在尝试在 python 中制作一个选项菜单,如果用户选择一个数字,则会执行不同的功能:
def options(x):
return {
1: f1(),
2: f2()
}[x]
def f1():
print "hi"
def f2():
print "bye"
不过,我叫好了
options(1)
我得到:
hi
bye
当我调用 options(2)
这是怎么回事?
最佳答案
您正在调用函数而不是将它们分配给键
def f1():
print "hi"
def f2():
print "bye"
functions = {1: f1, 2: f2} # dict of functions (Note: no parenthesis)
def options(x):
return functions[x]() # Get the function against the index and invoke it
options(1)
# hi
options(2)
# bye
关于python - 使用函数值访问 python dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22199417/