Python-使用列表作为函数参数

问题:Python-使用列表作为函数参数

如何使用Python列表(例如params = ['a',3.4,None])作为函数的参数,例如:

def some_func(a_char,a_float,a_something):
   # do stuff

How can I use a Python list (e.g. params = ['a',3.4,None]) as parameters to a function, e.g.:

def some_func(a_char,a_float,a_something):
   # do stuff

回答 0

您可以使用splat运算符执行此操作:

some_func(*params)

这使函数将每个列表项作为单独的参数接收。这里有一个描述:http : //docs.python.org/tutorial/controlflow.html#unpacking-argument-lists

You can do this using the splat operator:

some_func(*params)

This causes the function to receive each list item as a separate parameter. There’s a description here: http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists


回答 1

这已经得到了完美的答案,但是由于我刚进入本页并且不立即理解,所以我将添加一个简单但完整的示例。

def some_func(a_char, a_float, a_something):
    print a_char

params = ['a', 3.4, None]
some_func(*params)

>> a

This has already been answered perfectly, but since I just came to this page and did not understand immediately I am just going to add a simple but complete example.

def some_func(a_char, a_float, a_something):
    print a_char

params = ['a', 3.4, None]
some_func(*params)

>> a

回答 2

使用星号:

some_func(*params)

Use an asterisk:

some_func(*params)

回答 3

您需要参数解包运算符*。