调用函数时将列表转换为*参数

2024-09-24 02:24:22 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,如何将列表转换为*args

我需要知道因为函数

scikits.timeseries.lib.reportlib.Report.__init__(*args)

想要几个时间序列对象作为*args传递,而我有一个时间序列对象列表。


Tags: 对象函数report列表initlib时间args
3条回答

是的,使用*arg将args传递给函数将使python解压arg中的值并将其传递给函数。

所以:

>>> 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],)
>>> 

可以在iterable之前使用*运算符在函数调用中展开它。例如:

timeseries_list = [timeseries1 timeseries2 ...]
r = scikits.timeseries.lib.reportlib.Report(*timeseries_list)

(注意*之前的timeseries_list

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.

python教程在一个名为Unpacking argument lists的部分中也介绍了这一点,其中还演示了如何使用字典对带有**运算符的关键字参数执行类似的操作。

*args只表示函数接受许多参数,通常是相同类型的。

查看Python教程中的this section了解更多信息。

相关问题 更多 >