Describes the special use of asterisk variables in Python

Source: Internet
Author: User
In Python, in addition to multiplying numeric and exponentiation, there is a special use of "add a single asterisk or two asterisk before a variable" to implement a multi-parameter pass-through or a variable disassembly, which will be described in detail in the use of the asterisk parameter.

First, what is the asterisk variable

Initially, the asterisk variable is used in the function of the parameter pass, in the following instance, a single asterisk to receive any number of non-keyword parameters, in the *b position of the function to convert it to a tuple, and the double star represents this location to receive any number of keyword parameters, in the **b position to convert it into a dictionary:

#!/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 (a=1,**b): "" "  A is an ordinary keyword parameter, **b is a keyword double star" ""  print (b) , f=6)

#程序输出

(2, 3, 4, 5, 6) {' B ': 2, ' C ': 3, ' E ': 5, ' F ': 6, ' d ': 4}

#从输出中可以看到, in the first function, the position of *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))

#第二个函数中, the **b position can receive any number of keyword arguments, and the following call

Both (a=1,b=2,c=3,d=4,e=5,f=6)

#传入one (a,*b), equivalent to

Both (a=1,{' B ': 2, ' C ': 3, ' E ': 5, ' F ': 6, ' d ': 4})

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

Second, the single number of variable instances

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

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

#程序输出

Www.pythontab.comaw

#第一次调用one (STRI,LST), substituting one (*x) for equivalence with

One ((["A", "B", "C", "D"], "www.pythontab.com"))

#第二次调用one (*LST), substituting one (*x) for equivalence with

One (("A", "B", "C", "D"))

#第三次调用one (*stri), substituting one (*x) for equivalence with

One ("W", "W", "W", ".", "Q", "I", "N", "G", "s", "w", "O", "R", "D", ".", "C", "O", "M"))

#如果在变量前面使用单星号, it is actually a one-time disassembly of the variable, the individual elements of the variable are disassembled, and then passed in the one () function, and once passed in a () function, the single () function will save these incoming individual elements into a tuple, which is why we print (x [0]) The reason why the first element can be extracted

To verify this, let's modify the one () function, as follows:

#!/usr/bin/env python#coding=utf-8#--------def One (*x): "" "  an instance of an error that attempts to modify the first parameter value passed in, throwing an exception" ""  print (X[0])  x[0]= "Pythontab" lst=["a", "B", "C", "D"]one (*LST)

#我们知道列表是可以更改的, we split the list into the one () function, try to change the value of the first element inside the function, the result triggers the "TypeError" exception, and you can try it on your own, the reason for this is that the result is shown above, regardless of the original type of the incoming parameter, Once the one (*X) receives these incoming parameters in the *x location, it will be saved as a "tuple" and the tuple cannot be changed.

Let's look at a few more examples:

#!/usr/bin/env python#coding=utf-8#--------def One (*x): "" "  prints the Incoming parameter" ""  for A in x:    print (a) lst=["abc", 123, "www.pythontab.com"]stri= "ABCD" Dect={1: "One", 2: "One", 3: "Three"}one (*LST) One (*stri) one (*dect)

#程序输出

Abc123www.pythontab.comabcd123

#前面两次调用都很好理解, we finally passed in a dictionary element, found that only the key of the dictionary element is output, and does not contain the value, in fact, the single number is not readable to the value of the dictionary, will 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, the double star variable instance

At the end of the 2nd section, we use the single number to split a dictionary to a function, but only get the dictionary key, the following 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-in keyword parameter narimoto group output ""  print (x)  b= ()  For a In X.keys ():    b+= (X[a],)  print (b) dect={"One": 1, "one": 2, "three": 3}one (**dect)

#程序输出

{' Three ': 3, ' one ': 1, ' both ': 2} (3, 1, 2)

#对一个字典使用双星号前缀, it is equivalent to splitting it into the form of a keyword argument, **dect equivalent to splitting the dictionary into the following way

One=1,two=2,three=3

#将上面这些关键字参数传入one (**X), which is equivalent to (remember previously, the Double star will receive all the keyword parameters are saved into a dictionary bar)

One ({"One": 1, "one": 2, "three": 3})

#既然是字典, then all the methods in the dictionary can be used, using the for loop to iterate through the dictionary keys, 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 to a function, the name of the dictionary key should conform to the naming rules of the Python variable, it is not difficult to see through the above analysis, the double star will first convert the dictionary into the form of the keyword parameter, the equivalent of using the dictionary key as the variable name, if the key does not conform , a "TypeError" exception is thrown, and you can try to reverse the keys and values in the dictionary above, use numbers as keys, and see what happens.

In the receive parameter of a function, when the "non-keyword parameter (positional parameter)" and "keyword parameter" appear, you can use a single asterisk to separate the two parameters, for example:

#!/usr/bin/env python#coding=utf-8#--------def Mix (a,b,*,x,y): "" "  position parameter mixed with keyword parameter" "" "  return a,b,x,y# A and B in front of the asterisk are positional parameters, the X and y after the asterisk are the keyword arguments, the mix () function is called and passed into the parameter, the keyword argument must be passed in as "variable name = value", and if the data is passed in the same position parameter, a TypeError exception print (mix (1,2,x=3,y=4))

#程序输出

(1, 2, 3, 4)

#在上面的mix函数中, if a single asterisk positional parameter already exists between the positional parameter and the keyword parameter, then all of this parameter is followed by a keyword argument, and no need to use asterisks to separate them, for example

#!/usr/bin/env python#coding=utf-8#--------def Mix (a,b,*c,x,y): "" "  position parameter mixed with keyword parameter" "" "  return a,b,c,x,y# in * The position of C can be entered in 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 several parameters in a function, we must follow the order: Positional parameter (required parameter), 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): "" "  position parameter mixed with keyword parameter" "" "  return a,b,c,x, Yprint (Mix (1,2,3,4,5,x=6,y=7,z=8))

#程序输出

(1, 2, (3, 4, 5), 6, {' Y ': 7, ' Z ': 8})
Related Article

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.