Feed python function with a variable number of arguments

隐身守侯 提交于 2020-01-22 02:24:46

问题


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


回答1:


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')
>>>



回答2:


you should use args and kwargs like this:

def foo(*args, **kwargs):
  pass

in this way you can get positional and named parameters, args should be a list of values, holding the positional arguments, kwargs should be a dictionary, its keys the argument name with its value



来源:https://stackoverflow.com/questions/25062458/feed-python-function-with-a-variable-number-of-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!