赞
踩
I have a question here which is based around user input to scripts and passing this user-input to functions.
I have a script, within which I have defined a function. What I want the script to do is take user input to pass as arguments to the function. However, one of the things I want to pass to the function is the name of an argument rather than the argument itself. The user has the choice of using a variety of different lists to input to the function, and what I wanted was to get the user to input the name of the variable that they want to use.
Say I want to pass the argument Tablelist3 to the function. When I ask for the user input, and they input Tablelist3, what is being passed to the function is 'Tablelist3' as a string, rather than the variable itself.
How do I get it so that whichever variable the user names is the variable which gets passed to the function?
Hope my question makes sense and isn't too simple. I'm relatively inexperienced with Python.
解决方案
Use a dictionary, mapping strings to objects:
tbl1, tbl2 = [1 ,2 ,3], [4 ,5 ,6]
args = {'tbl1': tbl1 ,"tbl2" :tbl2}
# show tables ......
inp = input("Choose table")
def foo(var):
print(var)
foo(args[inp])
You will want to do error checking to make sure the user actually enters something valid.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。