开发者

How to split list and pass them as separate parameter?

Given the definitions:

def egg2(arg1, arg2):
    print arg1
    print arg2

argList = ["egg1", "egg2"]

How can I simply call egg2 using the list? I want the same effect as egg2(argL开发者_StackOverflow中文版ist[0], argList[1]), but without having to index each element explicitly.


>>> argList = ["egg1", "egg2"]
>>> egg2(*argList)
egg1
egg2

You can use *args (arguments) and **kwargs (for keyword arguments) when calling a function. Have a look at this blog on how to use it properly.


There is a special syntax for argument unpacking:

egg2(*argList)


There are maybe better ways, but you can do:

argList = ["egg1", "egg2"]
(a, b) = tuple(argList)
egg2(a, b)


arg.split() does not split the list the way you want because the default separator does not match yours:

In [3]: arg
Out[3]: 'egg1, egg2'

In [4]: arg.split()
Out[4]: ['egg1,', 'egg2']

In [5]: arg.split(', ')
Out[5]: ['egg1', 'egg2']

From the docs (emphasis added):

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜