python * args and ** kwargs sequence and unpacking

DAY 8. *args和**kwargs

*args: Multi-value tuples, **kwargsmulti-valued dictionaries, when they are python function parameter passing two special parameters, args and kwargs not mandatory, but the habit of using these two, if declared in the function parameter list *args, then allowed to pass any number of parameters of the extra parameters will be assigned the variable args tuple of the form, and **kwargsallows you to use the variable name is not defined, will pass parameters explicitly packaged into dictionaries

def output(*args, **kwargs):
    print(args)
    print(kwargs)

output('zhangsan', 'lisi', 5, 6,a=1,b=2,c=3)

# ('zhangsan', 'lisi', 5, 6)
# {'a': 1, 'b': 2, 'c': 3}

From left to right will control the function assignment if there are other parameters, passing parameters, so be sure to put *argsand **kwargson the last function parameter list, otherwise it will throw a TypeError exception, and *argsmust be placed in **kwargsfront of the correct order of the arguments should be

def fun(arg, *args, **kwargs):
    pass

It can also be used when calling the function *and**

def put(a, b, c):
    print(f'a={a},b={b},c={c}')

put(*mylist)  # a=aardvark,b=baboon,c=cat

s = {'a': 1, 'b': 2, 'c': 3}
put(**s)  # a=1,b=2,c=3

Has been able to achieve this function, the principle is the sequence unpacked, the following brief sequence unpacking

>>> s = "ABCDE"
>>> a,b,c,d,e = s
>>> a,c
('A', 'C')

>>> t = (1,2,3,4,5)
>>> a1,b1,c1,d1,e1 = t
>>> a1,c1
(1, 3)

The above sequence is used to unpack, left and right ends of the number of elements must be equal, otherwise it will throw ValueError exception

>>> a2,b2 = s
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    a2,b2 = s
ValueError: too many values to unpack (expected 2)

But we can not all sequences correspond to, if there are a lot of bit sequence or uncertain how many of the use of sequence unpacking it is very convenient, this time we can use *and the

>>> a3,*a4 = s
>>> a3,a4
('A', ['B', 'C', 'D', 'E'])
>>> while s:
        f,*s = s
        print(f,s)

A ['B', 'C', 'D', 'E']
B ['C', 'D', 'E']
C ['D', 'E']
D ['E']
E []

Reference article:

Detailed Python unpacking sequence (4)

stack overflow

See example from a sequence unpacking Python3.x

GitHub python face questions

Published 62 original articles · won praise 33 · views 10000 +

Guess you like

Origin blog.csdn.net/zjbyough/article/details/96511437