Python study notes day5 - 04 Parameters of the function - variable parameters*

The number of parameters passed in is variable.
Example: Define a function that, given a set of numbers, returns the sum of the maximum and minimum values ​​in the set.
    def msum(numbers):
        r = max(numbers) + min(numbers)
        return r
       
    >>>msum([1,2,3,4,5])
    6
    numbers need to be list or tuple, equivalent to:
    a = [ 1,2,3,4,5]
    msum(a)
   
If variadic parameters are used, the changes when calling the function are as follows:
    No variadic parameters are used: msum([1,2,3,4,5])
    can be used Variable parameters: msum(1,2,3,4,5)
Change the function parameter to variable parameter:
    def msum(*numbers):
        r = max(numbers) + min(numbers)
        return r
      
       result:
        >>> def msum(*numbers):
        ... r = max(numbers ) + min(numbers)
        ... return r
        ...
        >>> msum(1,2,3,4)
        5
        >>> msum(1,2,5,7,8,9,123,323123)
        323124
        in parameters After the prefix *, the parameter numbers receives a tuple, so if the code is completely unchanged, the calling function can pass in any number of parameters.
       
Call variadic
    If you already have a list or tuple, call a variadic method:
   
        >>> a = [1,2,3,4,5,6]
        >>> msum(a[0],a [1],a[2],a[3],a[4],a[5])
        7
   is too much trouble.
   Add the * sign before the list or tuple to turn the elements of the list or tuple into variable parameters and pass them into the function!
        >>> a = [1,2,3,4,5,6,7,8,10,12,123123123,122]
        >>> msum(*a)
        123123124
       
        *a means to use all elements of the list of a as Variable arguments are passed into the msum function.
        This way of writing is very common and very useful.
  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325244926&siteId=291194637