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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值