调用函数时将列表转换为 *args [英] Converting list to *args when calling function

查看:24
本文介绍了调用函数时将列表转换为 *args的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Python, how do I convert a list to *args?

我需要知道,因为函数

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

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

wants several time_series objects passed as *args, whereas I have a list of timeseries objects.

推荐答案

您可以在可迭代对象之前使用 * 运算符以在函数调用中扩展它.例如:

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)

(注意timeseries_list之前的*)

来自 python 文档:

如果函数调用中出现语法*expression,则表达式必须评估为可迭代的.来自这个迭代的元素被处理好像它们是附加的位置参数;如果有位置参数 x1、...、xN 和表达式的计算结果为序列 y1, ..., yM,这相当于调用了 M+N 个位置参数 x1, ..., xN, y1, ..., yM.

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 教程中包含在标题为 解包参数列表,其中还展示了如何使用 ** 运算符对关键字参数的字典执行类似的操作.

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.

这篇关于调用函数时将列表转换为 *args的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆