Several special usages of the asterisk variable in Python _python

Source: Internet
Author: User
Tags in python

First, what is the asterisk variable

Initially, the asterisk variable is used on the parameter pass of the function, in the example below, a single asterisk receives any number of non-critical parameters in this position, converts it to a tuple at the *b position of the function, and the double star represents the position to receive any number of keyword parameters and converts it to a dictionary at the **b position:

#!/usr/bin/env python
#coding =utf-8
#--------
def One (a,*b): ""
  A is a normal incoming parameter, *b is a non-keyword asterisk parameter
  "" " Print (b) one
(1,2,3,4,5,6)
#--------
def two (a=1,**b): ""
  A is a generic keyword parameter, **b is a keyword double star number parameter
  "" " Print (b)
two (a=1,b=2,c=3,d=4,e=5,f=6)

#程序输出
(2, 3, 4, 5, 6)
{' B ': 2, ' C ': 3, ' E ': 5, ' F ': 6, ' d ': 4}
    #从输出中可以看到, in the first function, the position of the *b can pass in any number of arguments without a keyword, *b will convert these incoming parameters into a tuple, the following call one
(1,2,3,4,5,6)
#传入one (a,*b), equivalent to
One (1, (2,3,4,5,6))

#第二个函数中, **b position can receive any number of keyword parameters, the following call
Two (a=1,b=2,c=3,d=4,e=5,f=6)
#传入one ( A,*B) after equivalence with
two (a=1,{' B ': 2, ' C ': 3, ' E ': 5, ' F ': 6, ' d ': 4})

After understanding the basic usage of single and double stars, let's look at their extended usage.

Second, single number variable example

Single variable can be used not only in the function of the parameter pass, in fact, a normal variable using the single prefix, can be split into a single element of the variable, see the following example:

#!/usr/bin/env python
#coding =utf-8
#--------
def One (*x): "" "
  output the first parameter passed in" ""
  print (x[0))
#--------
lst=["A", "B", "C", "D"]
stri= "www.qingsword.com" one (
stri,lst) One (
*lst) One (
* Stri)

#程序输出
www.qingsword.com
a
w

#第一次调用one (stri,lst) and substituting one (*x) is equivalent to one
((["A", "B "," C "," D "]," www.qingsword.com ")

#第二次调用one (*lst), substituting one (*x) after equivalent to one
((" A "," B "," C "," D "))

#第三次调用one (*stri), substituting one (*x) after equivalence with one
(("W", "W", "W", ".", "Q", "I", "N", "G", "s", "w", "O", "R", "D", ".", "C", "O", "M")

If you use the single number in front of the variable, it is actually a split operation on the variable, by splitting the individual elements in a variable and then passing in the one () function, and passing in the one () function, a one () function saves the incoming individual elements into a tuple, which is why we print (x[ 0] The reason for the first element to be extracted

To verify this, we modify the one() function as follows:

#!/usr/bin/env python
#coding =utf-8
#--------
def One (*x): "" "
  an instance of an error that attempted to modify the passed-in first parameter value, throwing an exception"
  " Print (x[0])
  x[0]= "Qingsword"

lst=["a", "B", "C", "D" "One"
(*lst)

#我们知道列表是可以更改的, we split the list and pass in the one () function, Attempt to change the value of the first element within a function. The result triggers the "TypeError" exception, and you can try it yourself, and the reason for this result is that, regardless of the original type of the incoming argument, one (*X) receives the incoming arguments at *x position and then saves them as " Tuples, and tuples cannot be changed

Let's look at a few more examples:

#!/usr/bin/env python
#coding =utf-8
#--------
def One (*x): ""
  print out incoming arguments "" 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)

#程序输出
ABC
123
www.qingsword.com
a
b
C
D
1
2
3

#前面两次调用都很好理解, finally we passed in a dictionary element and found that only the key of the dictionary element was exported, and the value was not included, in fact, the single number was not able to read the value in the dictionary, Always read only the keys in the dictionary, if you want to read the values in the dictionary, you need to use the double star

Three, double star number variable example

At the end of the 2nd section, we split a dictionary with the single number to pass to the function, but only the dictionary key, which shows how to use the double star to get the value of the dictionary:

#!/usr/bin/env python
#coding =utf-8
#--------
def One (**x): ""
  saves the value of the passed keyword parameter infinitesimal the group output "" "
  print (x )
  b= () for
  A in X.keys ():
    b+= (X[a],)
  print (b)

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

#程序输出
{' Three ': 3, ' one ': 1, ' two ': 2}
(3, 1, 2)

#对一个字典使用双星号前缀, which is equivalent to splitting it into the form of a keyword parameter, * * DECT is equivalent to splitting the dictionary into the following way
one=1,two=2,three=3

#将上面这些关键字参数传入one (**x), which is equivalent to (remember the previous, the double star will receive all the keyword parameters are saved into a dictionary) One
({"One": 1, "two": 2, "three": 3})

#既然是字典, all the methods in the dictionary can be used, use a for loop to traverse the dictionary's key, and then use a tuple to add the values corresponding to these keys, and finally print out the tuple

Ps: Note that when using this method to pass a dictionary into a function, the dictionary's key name should conform to the naming rules for Python variables, and it is easy to see from the above analysis that the double star will convert the dictionary first into the form of a keyword parameter, which is equivalent to using a key in the dictionary as a variable If the key does not conform to the variable naming rules, then throws a "TypeError" exception, you can try to reverse the dictionary above the keys and values, using the number as a key to see what the problem will occur.

You can use a single asterisk to separate both parameters in the Receive argument for a function, both non-keyword parameters (positional parameters) and keyword parameters, for example:

#!/usr/bin/env python
#coding =utf-8
#--------
def Mix (a,b,*,x,y):
  "" "" "" "" "" "" "" Return
  A , B,x,y

#星号前面的a和b是位置参数, the X and y following the asterisk are keyword parameters, and when you call the Mix () function and pass in the argument, the keyword parameter must be passed in the form of "Variable name = value", and if you pass in the data the same as the positional parameter, A TypeError exception
print (1,2,x=3,y=4)

#程序输出
(1, 2, 3, 4) is raised

#在上面的mix函数中, If a single asterisk position parameter already exists between the positional parameter and the keyword parameter, then the argument is followed by a keyword parameter, and there is no need to use an asterisk to separate them, such as
#!/usr/bin/env python
#coding = Utf-8
#--------
def Mix (a,b,*c,x,y): "" "" "" "" "" "" "" "" "Return
  a,b,c,x,y

#在 * C's position can enter any number of positional parameter values
print (Mix (1,2,3,4,5,x=6,y=7))
 
#程序输出
(1, 2, (3, 4, 5), 6, 7)

If we want to include a combination of many parameters in a function, we must follow the order: positional parameter (required), default parameter, single number parameter or asterisk separator, keyword parameter, double star parameter;

Take a look at the following example:

#!/usr/bin/env python
#coding =utf-8
#--------
def Mix (a,b=0,*c,x,**y):
  "" "" "" "" "" "" "" "" "" "" "" "" return
  a,b,c,x,y

print (1,2,3,4,5,x=6,y=7,z=8)
#程序输出
(1, 2, (3, 4, 5), 6, {' Y ': 7, ' Z ': 8})

Summarize

This is the full content of this article, I hope to learn or use Python can help, if you have questions you can message exchange.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.