如何将列表扩展为Python中的函数参数[duplicate]

时间:2021-08-05 23:21:27

This question already has an answer here:

这个问题已经有了答案:

Is there syntax that allows you to expand a list into the arguments of a function call?

是否存在允许您将列表扩展到函数调用的参数的语法?

Example:

例子:

# Trivial example function, not meant to do anything useful.
def foo(x,y,z):
   return "%d, %d, %d" %(x,y,z)

# List of values that I want to pass into foo.
values = [1,2,3]

# I want to do something like this, and get the result "1, 2, 3":
foo( values.howDoYouExpandMe() )

4 个解决方案

#1


126  

It exists, but it's hard to search for. I think most people call it the "splat" operator.

它是存在的,但是很难去寻找。我想大多数人都叫它“splat”操作员。

It's in the documentation as "Unpacking argument lists".

它在文档中是“解压参数列表”。

You'd use it like this: foo(*values). There's also one for dictionaries:

您可以这样使用它:foo(*值)。字典也有一个:

d = {'a': 1, 'b': 2}
def foo(a, b):
    pass
foo(**d)

#2


34  

You should use the * operator, like foo(*values) Read the Python doc unpackaging argument lists.

您应该使用*操作符,如foo(*值)读取Python文档解包参数列表。

Also, do read this: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

另外,请阅读:http://www.saltycrane.com/blog/2008/01/howtouse - argandkwargs-inpython/

def foo(x,y,z):
   return "%d, %d, %d" % (x,y,z)

values = [1,2,3]

# the solution.
foo(*values)

#3


8  

Try the following:

试试以下:

foo(*values)

This can be found in the Python docs as Unpacking Argument Lists.

这可以在Python文档中找到,作为解包参数列表。

#4


8  

That can be done with:

可以这样做:

foo(*values)

#1


126  

It exists, but it's hard to search for. I think most people call it the "splat" operator.

它是存在的,但是很难去寻找。我想大多数人都叫它“splat”操作员。

It's in the documentation as "Unpacking argument lists".

它在文档中是“解压参数列表”。

You'd use it like this: foo(*values). There's also one for dictionaries:

您可以这样使用它:foo(*值)。字典也有一个:

d = {'a': 1, 'b': 2}
def foo(a, b):
    pass
foo(**d)

#2


34  

You should use the * operator, like foo(*values) Read the Python doc unpackaging argument lists.

您应该使用*操作符,如foo(*值)读取Python文档解包参数列表。

Also, do read this: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

另外,请阅读:http://www.saltycrane.com/blog/2008/01/howtouse - argandkwargs-inpython/

def foo(x,y,z):
   return "%d, %d, %d" % (x,y,z)

values = [1,2,3]

# the solution.
foo(*values)

#3


8  

Try the following:

试试以下:

foo(*values)

This can be found in the Python docs as Unpacking Argument Lists.

这可以在Python文档中找到,作为解包参数列表。

#4


8  

That can be done with:

可以这样做:

foo(*values)