Pass elements of a list as arguments to a function in python

匿名 (未验证) 提交于 2019-12-03 02:53:02

问题:

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)

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

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?

回答1:

Try unpacking your list into positional arguments:

commands[com](*args)


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!