问题: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

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


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。