Python - 变量名称的用户输入,作为参数传递给函数 [英] Python - User input for name of a variable to pass as an argument to a function

查看:459
本文介绍了Python - 变量名称的用户输入,作为参数传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有一个问题,它基于用户对脚本的输入并将此用户输入传递给函数。

我有一个脚本,我已经定义了脚本一个函数。我想让脚本执行的是将用户输入作为参数传递给函数。然而,我想传递给函数的一个东西是参数的名称而不是参数本身。用户可以选择使用各种不同的列表来输入函数,我想要的是让用户输入他们想要使用的变量的名称。



假设我想将参数Tablelist3传递给函数。当我询问用户输入时,他们输入Tablelist3,传递给函数的是'Tablelist3'作为字符串,而不是变量本身。



我能得到它,以便用户所指定的变量是传递给函数的变量吗?



希望我的问题有道理,并不是太简单。

解决方案

使用字典,将字符串映射到对象:

  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])

您需要进行错误检查以确保用户输入了有效的内容。


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.

这篇关于Python - 变量名称的用户输入,作为参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆