Detailed Explanation of the Usage of * in python
- 2021-07-13 05:36:05
- OfStack
1, for the multiplication sign
2. Represents multiples, such as:
def T(msg,time=1):
print((msg+' ')*time)
T ( 'hi',3 )
Print results (print 3 times):
hi hi hi
3. Individual *
(1) For example: * parameter is used to accept any number of parameters and put them in a tuple.
>>> def demo(*p):
print(p)
>>> demo(1,2,3)
(1, 2, 3)
(2) When the function calls multiple parameters, it takes lists, tuples, collections, dictionaries and other iterable objects as arguments, and adds * in front of them
For example, * (1, 2, 3) interpreter will automatically unpack and then pass it to multiple univariate parameters (the number of parameters should correspond to the same).
>>> def d(a,b,c):
print(a,b,c)
>>> d(1,2,3)
1 2 3
>>> a=[1,2,3]
>>> b=[1,2,3]
>>> c=[1,2,3]
>>> d(a,b,c)
[1, 2, 3] [1, 2, 3] [1, 2, 3]
>>> d(*a)
1 2 3
Tip: Sequence unpacking should be processed before key parameters and ** parameters
4. Two * * such as: **parameter is used to receive multiple arguments in the form of assignments similar to key parameter 1 and put them into a dictionary (that is, convert the parameters of this function into a dictionary).
>>> def demo(**p):
for i in p.items():
print(i)
>>> demo(x=1,y=2)
('x', 1)
('y', 2)