传递一个列表作为参数的元素在Python函数 [英] Pass elements of a list as arguments to a function in python

查看:171
本文介绍了传递一个列表作为参数的元素在Python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要建在python简单的跨preTER和我有麻烦处理的参数不同的数字来我的功能。我目前的方法是得到命令/参数列表如下:

I'm building a simple interpreter in python and I'm having trouble handling differing numbers of arguments to my functions. My current method is to get a list of the commands/arguments as follows.

args = str(raw_input('>> ')).split()
com = args.pop(0)

然后执行COM,我检查,看它是否是我的命令 - > code映射的字典,如果是我叫我已经存储在那里的​​功能。对于没有参数的命令,这将是这样的:

Then to execute com, I check to see if it is in my dictionary of command-> code mappings and if it is I call the function I have stored there. For a command with no arguments, this would look like:

commands[com]()

但是,如果一个命令有多个参数,我想这样的:

However, if a command had multiple arguments, I would want this:

commands[com](args[0],args[1])

有一些诀窍,我可以通过我的ARG名单给函数的元素,我试图调用部分(或全部)?还是有实施这种无需使用Python的CMD类的更好的办法?

Is there some trick where I could pass some (or all) of the elements of my arg list to the function that I'm trying to call? Or is there a better way of implementing this without having to use python's cmd class?

推荐答案

尝试

commands[com](*args)

这篇关于传递一个列表作为参数的元素在Python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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