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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4979542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:26:12  来源:igfitidea点击:

Python - use list as function parameters

pythonlistfunction-parameter

提问by Jonathan

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

采纳答案by Neil Vass

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

回答by Mark Byers

Use an asterisk:

使用星号:

some_func(*params)

回答by btilly

You want the argument unpackingoperator *.

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

回答by Michael David Watson

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