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

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

问题描述

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

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:

文件1,其字段为:A,B和C => function(A,B,C)

文件N,其字段为:A,B,C和D => function(A,B,C,D)

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:当然,该函数可以接受任意数量的参数

PD: Of course the function accepts any number of arguments

推荐答案

将字段(参数)读取到列表中,然后使用

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

function(*fields)

下面是一个演示:

>>> 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天全站免登陆