Python collection parameters (variable parameter) * para ** para and using

Collection parameters also known as variable parameters, because sometimes we do not know how many input parameters, it is necessary that all input parameters packed into an input parameter, which is to collect parameters, the two formats, one is collecting tuple * para, one is collected ** para dictionary, the following term use.

def test(*para):
	print('输入参数个数:',len(para))
	print(para)
test(1,2,3,4,5,6)

Here Insert Picture Description
Notice the difference:

def test(*para):
 print('输入参数个数:',len(para))
 print(*para)
test(1,2,3,4,5,6)

Here Insert Picture Description
If a single parameter representing a plurality of parameters, it is noted that when the input a parameter, as follows:

def test(*para):
 print('输入参数个数:',len(para))
 print(para)

a = (1,2,3,4,5,6) # 输入参数为元组
test(a)

Here Insert Picture Description

def test(*para):
 print('输入参数个数:',len(para))
 print(*para) # 差别在这,一个有引号一个没有
a = (1,2,3,4,5,6) # 这里的输入参数为元组
test(a)

Here Insert Picture Description
In this case the input parameters print There are no asterisk * are the same input tuple, but if the input parameters stored list is not the same, look at the following two examples:

def test(*para):
 print('输入参数个数:',len(para))
 print(para)

a = [1,2,3,4,5,6]
test(a)

Here Insert Picture Description

def test(*para):
 print('输入参数个数:',len(para))
 print(*para)

a = [1,2,3,4,5,6]
test(a)

Here Insert Picture Description
Did not see the difference, the above is a tuple, but the following is a list.


If there are other parameters in addition to collecting the necessary parameters, it is best to specify the default parameters, and the need to specify parameter names when calling functions, such as:

def test(*para,two = 0):
 print('输入参数个数:',len(para))
 print(para)
 print(two)

a = {1:'one',2:'tow'}
test(a,2)

Here Insert Picture Description
This shows that all input parameters are understood became collection parameters, other parameters are assigned if you need to, to read:

def test(*para,two = 0):
 print('输入参数个数:',len(para))
 print(para)
 print(two)

a = {1:'one',2:'tow'}
test(a,two = 2)

Here Insert Picture Description


Look at two asterisks ** para input parameters

def test(**para):
 print('输入参数个数:',len(para))
 print(para)

test(a = 1,b = 2)

Here Insert Picture Description
At this point is the return of the dictionary.

Published 58 original articles · won praise 69 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_43157190/article/details/104753398