Python - 使用list作为函数参数

时间:2022-03-31 11:00:57

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

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

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

4 个解决方案

#1


112  

You can do this using the splat operator:

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

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

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

#2


45  

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

#3


14  

Use an asterisk:

使用星号:

some_func(*params)

#4


9  

You want the argument unpacking operator *.

你想要参数解包运算符*。

#1


112  

You can do this using the splat operator:

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

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

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

#2


45  

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

#3


14  

Use an asterisk:

使用星号:

some_func(*params)

#4


9  

You want the argument unpacking operator *.

你想要参数解包运算符*。