当前位置:   article > 正文

python定义输入变量_Python - 变量名称的用户输入,作为参数传递给函数

python将变量名作为参数传递

1586010002-jmsa.png

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.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/356219
推荐阅读
相关标签
  

闽ICP备14008679号