如何拆分列表并将其作为单独的参数传递?

2024-06-30 16:51:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题是列表中有值。我想分离这些值,并将它们作为单独的参数发送

我的代码是:

def egg():
    return "egg"

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

argList = ["egg1", "egg2"]
arg = ', '.join(argList)

egg2(arg.split())

这行代码(egg2(arg.split()))不起作用,但我想知道是否可以调用一些内置函数,将值从列表中分离出来,因此稍后我们可以将它们作为两个不同的参数发送。与egg2(argList[0], argList[1])类似,但需要动态执行,因此不必显式键入列表参数


Tags: 代码列表参数returneggdefargsplit
3条回答

argument unpacking有一种特殊的语法:

egg2(*argList)

arg.split()未按您希望的方式拆分列表,因为默认分隔符与您的不匹配:

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

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

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

the docs(加上强调):

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.

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

调用函数时,可以使用*args(参数)和**kwargs(关键字参数)。 看看this blog如何正确使用它

相关问题 更多 >