python - 如何存储然后调用同一字典中的字符串和函数?
问题描述
我一直在尝试在字典中存储然后调用字符串和/或函数。
第一个例子
def mainfunction():
dict = {
'x' : secondfunc,
'y' : 'hello world'
}
while True :
inpt = input('@')
dict[inpt]()
def secondfunc():
print('hi world')
mainfunction()
这仅在我输入键“x”时才有效。如果我尝试输入键 'y',我会收到此错误。
TypeError: 'str' object is not callable
此外,这种方法的问题是它无法做出默认答案。
第二个例子
def mainfunction():
dict = {
'x' : secondfunc,
'y' : 'hello world'
}
while True:
inpt = input('@')
z = dict.get(inpt, 'Default text')
print(z)
def secondfunc():
print('hi world')
mainfunction()
此方法适用于键 'y',但对于键 'x',它会打印以下内容:
<function secondfunc at 0x7ab4496dc0>
我试图让它无论我输入哪个值,它都会打印一个默认值,打印一个字符串,或者执行一个函数。一切都取决于按键输入。
最后一个例子
我发现的唯一解决方案是使用if
语句的解决方案。
def mainfunction():
dict = {
'x' : secondfunc,
}
dict2 = {
'y' : 'hello world'
}
while True:
inpt = input('@')
z = dict2.get(inpt, 'Default text')
if inpt == 'x':
dict[inpt]()
else:
print(z)
def secondfunc():
print('hi world')
mainfunction()
这个解决方案需要的代码比我想要的要多,而且它还需要一个if
特定于给定字典的语句,这需要更多时间。有没有更好的方法来做到这一点?
解决方案
您需要在字典中存储一个返回字符串的函数,而不是字符串本身。
最简单的是,这可以使用以下lambda
语法作为匿名函数来完成:
answers = {
'x': secondfunc,
'y': lambda: 'hello world'
}
(命名这个字典是不好的做法dict
,因为它会影响内置的dict
,所以我会在这里使用一个更好的名字。)
当然,secondfunc
不应该打印一个字符串,而是返回一个字符串,因为打印已经是工作mainfunc
(另见:Python 中返回和打印的区别?):
def secondfunc():
return 'hi world'
现在,print(answers['x']())
并且print(answers['y']())
正在平等地工作。
要使用字典方法创建默认答案.get()
,它还需要是一个返回字符串的函数:
def mainfunction():
answers = {
'x' : secondfunc,
'y' : lambda: 'hello world'
}
while True:
inpt = input('@')
z = answers.get(inpt, lambda: 'Default text')()
print(z)
推荐阅读
- html - 如何配置模态窗口以适应包含图像的实际大小?
- ios - 在系统提供的 UILabel 动画期间允许用户与 UIButton 交互
- python-3.x - 导入安装在 conda 环境中的包时出现 ModuleNotFoundError
- python - Ubuntu 18.04 上的 JModelica
- svg - textArea SVG 元素未出现在 FireFox 中
- parsing - 解包嵌套的应用函子 f#
- java - 未找到产品名称的 DatabaseType:[Impala]
- javascript - 将音频从 mongodb 传递到音频标签
- c - Netbeans C项目配置需要编译
- python - 如果多列中的值停留在单个值,请使用 Python 更改为 NaN