我正在尝试制作lambda函数的字典。它应该能够获取键并处理绑定到该键的任何功能,然后输出结果。
func_dict = {
"func1" : (z = lambda x, y: x + y),
"func2" : (z = lambda x, y: x * y)
} # include benchmark functions
func = input("Choose a function: ")
output = func_dict[func](3, 5)
print(output)
该示例应显示8
,但无法运行,并且简单地显示了can't assign to dictionary display
的错误
{
"func1" : (z = lambda x, y: x + y),
"func2" : (z = lambda x, y: x * y)
}
(缩进似乎不是问题)
我想避免使用eval()
和exec()
。
答案 0 :(得分:9)
您的初次尝试将引发语法错误。
相反,您希望将lambda函数的定义直接分配给键,如下所示:
#The lambda function is assigned as a value of the keys
func_dict = {
"func1" : lambda x, y: x + y,
"func2" : lambda x, y: x * y
}
func = input("Choose a function: ")
output = func_dict[func](3, 5)
print(output)
输出将为
Choose a function: func1
8
Choose a function: func2
15
答案 1 :(得分:4)
我认为您对z =
的分配很糟糕。
尝试
func_dict = {
"func1" : lambda x, y: x + y,
"func2" : lambda x, y: x * y
} # include benchmark functions
这对我有用:
❯❯❯ python
Python 3.6.7 (default, Dec 3 2018, 11:24:55)
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.10.44.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> func_dict = {
"func1" : lambda x, y: x + y,
"func2" : lambda x, y: x * y
} # include benchmark functions... ... ...
>>> func_dict["func1"](1,2)
3
答案 2 :(得分:1)
您的字典很好。
func_dict = {
"func1" : lambda x, y: x + y,
"func2" : lambda x, y: x * y
} # include benchmark functions
func = input("Choose a function: ")
output = func_dict[func](3, 5)
print(output)