Python:通过用户输入从字典调用函数
我正在尝试使用字典键调用函数。目前字典中只有一个函数,但我计划添加更多。下面的代码用于显示列表,因为函数“loadlist”没有参数,并且我在以f打开文件时已将“gameone.txt”写入了主体代码 我希望将文件名作为loadlist函数的参数,以便用户键入例如。。。loadlist('gameone.txt')或loadlist('gametwo.txt')等,具体取决于他们希望显示的内容Python:通过用户输入从字典调用函数,python,Python,我正在尝试使用字典键调用函数。目前字典中只有一个函数,但我计划添加更多。下面的代码用于显示列表,因为函数“loadlist”没有参数,并且我在以f打开文件时已将“gameone.txt”写入了主体代码 我希望将文件名作为loadlist函数的参数,以便用户键入例如。。。loadlist('gameone.txt')或loadlist('gametwo.txt')等,具体取决于他们希望显示的内容 def interact(): command = raw_input('Command:') d
def interact():
command = raw_input('Command:')
def loadlist():
with open('gameone.txt', 'r') as f:
for line in f:
print line
dict = {'loadlist': loadlist}
dict.get(command)()
return interact()
相互作用()
我尝试了下面的代码,但我无法解决我的问题
def interact():
command = raw_input('Command:')
def loadlist(list):
with open(list, 'r') as f:
for line in f:
print line
dict = {'loadlist': loadlist}
dict.get(command)()
return interact()
相互作用()
感谢您的输入。您可以尝试使用*args
def interact():
command,file_to_load = raw_input('Command:').split(' ')
# *args means take the parameters passed in and put them in a list called args
def loadlist(*args):
# get the argument from args list
filename = args[0]
with open(filename, 'r') as f:
for line in f:
print line
dict = {'loadlist': loadlist}
dict.get(command)(file_to_load)
interact()
下面是一篇关于stackoverflow的优秀文章,其中提供了一些可能会有所帮助的高质量答案:请注意,您不应该使用隐藏内置类型的变量名(即list、dict)