Several special USES of the asterisk variable in python

  • 2020-05-10 18:24:22
  • OfStack

1. What is the asterisk variable

Initially, the asterisk variable is used in the function arguments, in the example below, a single asterisk represents the position to receive any number of non-critical character parameter, the function of * b place it into a tuple, and binary number represents the position to receive any number of keyword arguments, b in * * position it into the dictionary:


#!/usr/bin/env python
#coding=utf-8
#--------
def one(a,*b):
  """a is 1 Two ordinary incoming parameters, *b is 1 Non-keyword asterisk parameters """
  print(b)
one(1,2,3,4,5,6)
#--------
def two(a=1,**b):
  """a is 1 Common keyword parameters, **b is 1 Two key words double star parameter """
  print(b)
two(a=1,b=2,c=3,d=4,e=5,f=6)

# Program output 
(2, 3, 4, 5, 6)
{'b': 2, 'c': 3, 'e': 5, 'f': 6, 'd': 4}

# As you can see from the output, no 1 Of the functions, *b As many parameters without keywords can be passed in, *b These incoming parameters are converted to 1 Tuples, the following call 
one(1,2,3,4,5,6)
# The incoming one(a,*b) Is equivalent to 
one(1,(2,3,4,5,6))

# The first 2 Of the functions, **b The location can receive any number of keyword parameters as called below 
two(a=1,b=2,c=3,d=4,e=5,f=6)
# The incoming one(a,*b) Is equivalent to 
two(a=1,{'b': 2, 'c': 3, 'e': 5, 'f': 6, 'd': 4})

Now that you know the basic ways to use a single star and a double star, let's look at their extended USES.

2. Single asterisk variable instance

A single asterisk variable can be used not only in function parameter passing, but in fact, a single asterisk prefix can be used for a normal variable, which can be split into a single element. See the following example:


#!/usr/bin/env python
#coding=utf-8
#--------
def one(*x):
  """ Output the incoming number 1 A parameter """
  print(x[0])
#--------
lst=["a","b","c","d"]
stri="www.qingsword.com"
one(stri,lst)
one(*lst)
one(*stri)

# Program output 
www.qingsword.com
a
w

# The first 1 Time to call one(stri,lst) The substitution one(*x) After the equivalent to 
one((["a","b","c","d"],"www.qingsword.com"))

# The first 2 Time to call one(*lst) The substitution one(*x) After the equivalent to 
one(("a","b","c","d"))

# The first 3 Time to call one(*stri) The substitution one(*x) After the equivalent to 
one(("w","w","w",".","q","i","n","g","s","w","o","r","d",".","c","o","m"))

# If you use a single asterisk before a variable, you're actually referring to the variable 1 A secondary unpacking operation, in which the individual elements of a variable are taken apart and passed in turn one() Function, and pass it in one() After the function, one() The function saves these incoming individual elements as 1 Mu tuples, that's why we  print(x[0]) Be able to extract regulation 1 Cause of the elements 

To verify this point, let's modify it 1 one() The function is as follows:


#!/usr/bin/env python
#coding=utf-8
#--------
def one(*x):
  """1 Error instances, trying to modify the incoming 1 An exception is thrown """
  print(x[0])
  x[0]="qingsword"

lst=["a","b","c","d"]
one(*lst)

# We know that the list can be changed, so we split the list and pass it in one() Function to try to change the value inside the function 1 The result is triggered "TypeError" Exception, you can try it out on your own, and the reason for this is that no matter what the primitive type of the parameter you're passing in, one(*x) in *x After receiving the parameters passed in, it will be saved as " tuples " And tuples can't be changed 

A few more examples:


#!/usr/bin/env python
#coding=utf-8
#--------
def one(*x):
  """ Print out the incoming parameter """
  for a in x:
    print(a)

lst=["abc",123,"www.qingsword.com"]
stri="abcd"
dect={1:"one",2:"two",3:"three"}
one(*lst)
one(*stri)
one(*dect)

# Program output 
abc
123
www.qingsword.com
a
b
c
d
1
2
3

# The first two calls were easy to understand, and finally we passed them in 1 In fact, the single asterisk cannot read the value in the dictionary, only the key in the dictionary will be read. If you want to read the value in the dictionary, you need to use the double star 

3. Example of double star variable

At the end of section 2, we split a dictionary and passed it to the function using a single asterisk, only to get the key of the dictionary. Here's how to use a double star to get the value of the dictionary:


#!/usr/bin/env python
#coding=utf-8
#--------
def one(**x):
  """ Saves the value of the incoming keyword parameter as a tuple output """
  print(x)
  b=()
  for a in x.keys():
    b+=(x[a],)
  print(b)

dect={"one":1,"two":2,"three":3}
one(**dect)

# Program output 
{'three': 3, 'one': 1, 'two': 2}
(3, 1, 2)

# right 1 The use of a two-star prefix in a dictionary is equivalent to breaking it up into keyword arguments, **dect This is equivalent to splitting the dictionary into the following 
one=1,two=2,three=3

# Pass in the above keyword parameters one(**x) , is equivalent to (remember earlier, the binary saves all received keyword parameters as 1 A dictionary.) 
one({"one":1,"two":2,"three":3})

# Since it's a dictionary, all the methods in the dictionary can be used for Loop through the keys of the dictionary and use them 1 To add the corresponding values for these keys, and finally print out the tuple 

Ps: note that when using this method the dictionary into the function, the keys of the dictionary named python for variable naming rules, also it is not hard to see through the above analysis, binary number dictionary will be firstly converted to the form of a keyword arguments, as a variable name is equivalent to use a dictionary in the key, if the key is not in conformity with the variable naming rules, will throw a "TypeError" exception, you can try to reverse one above the keys and values in the dictionary, use digital as the key, and see what will happen.

When "non-keyword parameter (position parameter)" and "keyword parameter" appear simultaneously in the received parameter of 1 function, a single asterisk can be used to separate the two parameters, for example:


#!/usr/bin/env python
#coding=utf-8
#--------
def mix(a,b,*,x,y):
  """ The position parameter is mixed with the keyword parameter """
  return a,b,x,y

# Before the asterisk a and b It's the position parameter, after the asterisk x and y Is a keyword parameter called mix() Function and pass in parameters when the keyword parameter 1 Need to use " The variable name = value " The form of the incoming data, if the same location parameter 1 If the sample is passed in, it will be thrown 1 a TypeError abnormal 
print(mix(1,2,x=3,y=4))

# Program output 
(1, 2, 3, 4)

# In the above mix Function if the location parameter and the keyword parameter already exist 1 Single asterisk position parameter, then, this parameter is followed by the keyword parameter, they do not need to use the asterisk to separate them, for example 
#!/usr/bin/env python
#coding=utf-8
#--------
def mix(a,b,*c,x,y):
  """ The position parameter is mixed with the keyword parameter """
  return a,b,c,x,y

# in *c Can enter any number of position parameter values 
print(mix(1,2,3,4,5,x=6,y=7))
 
# Program output 
(1, 2, (3, 4, 5), 6, 7)

If we want to include multiple combinations of parameters in a function, we must follow the following order: position parameter (required), default parameter, single asterisk parameter or asterisk separator, keyword parameter, double star parameter;

See the following example:


#!/usr/bin/env python
#coding=utf-8
#--------
def mix(a,b=0,*c,x,**y):
  """ The position parameter is mixed with the keyword parameter """
  return a,b,c,x,y

print(mix(1,2,3,4,5,x=6,y=7,z=8))
# Program output 
(1, 2, (3, 4, 5), 6, {'y': 7, 'z': 8})

conclusion

The above is the whole content of this article, I hope to help you to learn or use python, if you have any questions, you can leave a message to communicate.


Related articles: