将列表的元素作为参数传递给python中的函数 [英] Pass elements of a list as arguments to a function in python
问题描述
我正在用 python 构建一个简单的解释器,但在处理函数的不同数量的参数时遇到了问题.我目前的方法是获取命令/参数列表,如下所示.
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,我检查它是否在我的命令字典中 -> 代码映射,如果是,我调用我存储在那里的函数.对于没有参数的命令,这看起来像:
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?
推荐答案
尝试将列表解包为位置参数:
Try unpacking your list into positional arguments:
commands[com](*args)
这篇关于将列表的元素作为参数传递给python中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!