Python 调用函数时将列表转换为 *args
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3941517/
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
Converting list to *args when calling function
提问by andreas-h
In Python, how do I convert a list to *args?
在 Python 中,如何将列表转换为*args?
I need to know because the function
我需要知道,因为函数
scikits.timeseries.lib.reportlib.Report.__init__(*args)
wants several time_series objects passed as *args, whereas I have a list of timeseries objects.
想要几个 time_series 对象作为 传递*args,而我有一个时间序列对象列表。
采纳答案by Bryan Oakley
You can use the *operator before an iterable to expand it within the function call. For example:
您可以*在可迭代对象之前使用运算符在函数调用中扩展它。例如:
timeseries_list = [timeseries1 timeseries2 ...]
r = scikits.timeseries.lib.reportlib.Report(*timeseries_list)
(notice the *before timeseries_list)
(注意*之前timeseries_list)
From the python documentation:
If the syntax *expression appears in the function call, expression must evaluate to an iterable. Elements from this iterable are treated as if they were additional positional arguments; if there are positional arguments x1, ..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM.
如果语法 *expression 出现在函数调用中,则表达式的计算结果必须为可迭代对象。来自这个可迭代对象的元素被视为额外的位置参数;如果存在位置参数 x1, ..., xN,并且表达式计算结果为序列 y1, ..., yM,则这相当于具有 M+N 个位置参数 x1, ..., xN, y1, ... 的调用。 ..,yM。
This is also covered in the python tutorial, in a section titled Unpacking argument lists, where it also shows how to do a similar thing with dictionaries for keyword arguments with the **operator.
这也包含在 python 教程中,在标题为Unpacking argument lists的部分中,它还展示了如何使用**运算符对关键字参数的字典执行类似的操作。
回答by intuited
*argsjust means that the function takes a number of arguments, generally of the same type.
*args只是意味着该函数采用许多参数,通常是相同的类型。
Check out this sectionin the Python tutorial for more info.
查看Python 教程中的这一部分以获取更多信息。
回答by Ant
yes, using *arg passing args to a function will make python unpack the values in arg and pass it to the function.
是的,使用 *arg 将 args 传递给函数将使 python 解压 arg 中的值并将其传递给函数。
so:
所以:
>>> def printer(*args):
print args
>>> printer(2,3,4)
(2, 3, 4)
>>> printer(*range(2, 5))
(2, 3, 4)
>>> printer(range(2, 5))
([2, 3, 4],)
>>>

