Unpacking is to extract each element of a sequence or map separately, and a simple use of a sequence unpacking is to extract the first or previous elements separately from the following elements, for example:
First, seconde, *rest = sequence
If there are at least three elements in the sequence, then after executing the above code, first = = Sequence[0], second = = Sequence[0], rest = = sequence[2:].
function receives indeterminate parameter
When the parameters of a function are indeterminate, you can use *args and **kwargs,*args without a key value, **kwargs has a key value.
| 12345678910111213141516171819202122232425 |
#!/usr/bin/python # -*- coding:utf-8 -*- importsys reload(sys) sys.setdefaultencoding(‘utf-8‘) ‘‘‘ 当函数的参数不确定时,可以使用*args 和**kwargs,*args 没有key值,**kwargs有key值。 ‘‘‘ deffun_var_args_kwargs(data1, *args, **kwargs): print‘data1:‘, type(data1), data1 print‘*args:‘, type(args), args print‘**kwargs:‘, type(kwargs), kwargs fun_var_args_kwargs(‘this is data1‘, 2, ‘3‘, 4.0, k1=‘value1‘, k2=‘value2‘) print‘-------------‘ defprint_args(*args, **kwargs): printargs.__class__.__name__, args, kwargs.__class__.__name__, kwargs print_args() print_args(1, 2, 3, a=‘A‘) |
Printing results:
| 123456 |
data1: <type‘str‘> this is data1 *args: <type‘tuple‘> (2, ‘3‘, 4.0) **kwargs: <type‘dict‘> {‘k2‘: ‘value2‘, ‘k1‘: ‘value1‘} ------------- tuple () dict {} tuple (1, 2, 3) dict {‘a‘: ‘A‘} |
Python sequence and map unpacking operations