python - 将参数传递给字典中的函数

标签 python dictionary switch-statement function-calls

我有一个类似开关的东西,给定一个选项将调用一个函数,例如

#... capture option
op = getOption()
#.. capture metric
mt = getMetric()

def zipcode():
    print "You typed zero.\n"
def desc():
    print "n is a perfect square\n"
def address():
    print "n is an even number\n"

#call desired option
options= {0 : zipcode,
          1 : code,
          2 : desc,
          3 : address
}

options[op]()

我正在尝试将参数(mt)传递到我的选项字典中,该字典将调用函数,但我无法这样做。

如果收到的 op 是 1 并且 mt 是 foo,如何通过传递 mt 作为参数来调用正确的函数(zipcode)?

理想情况下:options[op](mt) 并在函数中定义一个参数?

谢谢

最佳答案

您的代码缩进不正确,这在 Python 中非常重要,并且会导致语法错误。

但是,您的建议非常有效。

考虑以下因素:

def multiply(m,n):
    return n*n

def add(m,n)
    return m,n

my_math = { "+":add,
            "*":multiply}

然后您可以按如下方式调用它:

>>> print my_math["+"](1,2)
3
>>> print my_math["*"](4,5)
20

关于python - 将参数传递给字典中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29088813/

相关文章:

c# - 使用 LINQ 将 Dictionary<String,Int> 转换为 Dictionary<String,SomeEnum>?

jquery - 如何使用 jquery 切换 li id ='' Sprite 背景

python - cx_freeze 错误 "cx_Freeze.freezer.ConfigError: no base named Console"

python - 热图上的特定异常值 - matplotlib

python动态创建字典的字典

java - Java 13 中的新关键字 "yield"是什么意思?

R:如何使 switch 语句失效

python - 将 MatplotLib 或自定义颜色图应用于 OpenCV 图像

Python:除了以数字开头的字符串之外,是否有单行脚本来标题大小写字符串?

ios - 如何将数组的数组放入 Swift 1.2 中的另一个数组