使用可变数量的参数馈送 python 函数 [英] Feed python function with a variable number of arguments

查看:27
本文介绍了使用可变数量的参数馈送 python 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,可以从输入文件中读取可变数量的字段并将它们作为参数传递给函数.例如:

<块引用>

包含字段的文件 1:A、B 和 C => function(A,B,C)

带有字段的文件 N:A、B、C 和 D => function(A,B,C,D)

我的问题是:如何根据输入文件为函数提供正确数量的字段?

PD:当然该函数接受任意数量的参数

解决方案

将字段(参数)读入一个列表,然后使用 参数解包:

function(*fields)

以下是演示:

<预><代码>>>>def func(*args):...返回参数...>>>字段 = ["A", "B", "C"]>>>功能(*字段)('A', 'B', 'C')>>>字段 = [A"、B"、C"、D"]>>>功能(*字段)('A B C D')>>>

I have a script that reads a variable number of fields from an input file and pass them to a function as arguments. For example:

file 1 with fields: A,B and C => function(A,B,C)

file N with fields: A,B,C and D => function(A,B,C,D)

My question is: How to feed the function with the right number of fields accordingly to the input file?.

PD: Of course the function accepts any number of arguments

解决方案

Read the fields (arguments) into a list and then use argument unpacking:

function(*fields)

Below is a demonstration:

>>> def func(*args):
...     return args
...
>>> fields = ["A", "B", "C"]
>>> func(*fields)
('A', 'B', 'C')
>>> fields = ["A", "B", "C", "D"]
>>> func(*fields)
('A', 'B', 'C', 'D')
>>>

这篇关于使用可变数量的参数馈送 python 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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