Feed python function with a variable number of arguments

前端 未结 2 1479
逝去的感伤
逝去的感伤 2021-01-29 00:10

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 a

相关标签:
2条回答
  • 2021-01-29 00:19

    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')
    >>>
    
    0 讨论(0)
  • 2021-01-29 00:36

    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

    0 讨论(0)
提交回复
热议问题