使用可变数量的参数馈送 python 函数 [英] Feed python function with a variable number of arguments
问题描述
我有一个脚本,可以从输入文件中读取可变数量的字段并将它们作为参数传递给函数.例如:
<块引用>包含字段的文件 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屋!