search
HomeBackend DevelopmentPython TutorialSeveral special uses of asterisk variables in python

In addition to being used for multiplication numerical operations and exponentiation operations, asterisks in Python also have a special usage of "adding a single asterisk or two asterisks before a variable" to achieve the incoming of multiple parameters or the disassembly of variables. This article will introduce the usage of "asterisk parameter" in detail.

1. What is an asterisk variable?

Initially, asterisk variables are used to pass parameters of functions. In the following example, a single asterisk represents that this position receives any number of non-keyword parameters. In the function Convert it into a tuple at the *b position, and the double asterisk means that this position receives any number of keyword parameters, and convert it into a dictionary at the **b position:

#!/usr/bin/env python
#coding=utf-8
#--------
def one(a,*b):
  """a是一个普通传入参数,*b是一个非关键字星号参数"""
  print(b)
one(1,2,3,4,5,6)
#--------
def two(a=1,**b):
  """a是一个普通关键字参数,**b是一个关键字双星号参数"""
  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, in the first function, any number of parameters without keywords can be passed in at the *b position, and *b will convert these incoming parameters into a tuple, The following call

one(1,2,3,4,5,6)

# After passing in one(a,*b), it is equivalent to

one(1,(2,3,4,5 ,6))


#In the second function, the position of **b can receive any number of keyword parameters. The following call

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

#After passing in one(a,*b), it is equivalent to

two(a=1,{'b': 2, 'c': 3, ' e': 5, 'f': 6, 'd': 4})

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

2. Examples of single asterisk variables

Single asterisk variables can not only be used in parameter transfer of functions. In fact, using a single asterisk prefix for an ordinary variable can split the variable into single elements. Please see The following example:

#!/usr/bin/env python
#coding=utf-8
#--------
def one(*x):
  """输出传入的第一个参数"""
  print(x[0])
#--------
lst=["a","b","c","d"]
stri="www.pythontab.com"
one(stri,lst)
one(*lst)
one(*stri)


#Program output

www.pythontab.com
a
w

#The first time one(stri,lst) is called, after substituting one(*x), it is equivalent to

one(([ "a","b","c","d"],"www.pythontab.com"))


#Call one(*lst) for the second time, substitute one(*x) and wait The price is the same as

one(("a","b","c","d"))


#The third time one(*stri) is called, after substituting one(*x), it is equivalent to

one(("w","w","w",".","q","i","n","g","s","w","o"," r","d",".","c","o","m"))


#If you use a single asterisk in front of a variable, it is actually a disassembly operation of the variable. Decompose the individual elements in the variable, and then pass them into the one() function one by one. After passing in the one() function, the one() function will save these passed in single elements into a tuple, which is why we The reason why print(x[0]) can extract the first element

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

#!/usr/bin/env python
#coding=utf-8
#--------
def one(*x):
  """一个错误的实例,尝试修改传入的第一个参数值,引发异常"""
  print(x[0])
  x[0]="pythontab"
lst=["a","b","c","d"]
one(*lst)

#We know that the list can be changed, we will After the list is split, the one() function is passed in, and an attempt is made to change the value of the first element within the function. As a result, a "TypeError" exception is triggered. You can try it yourself. The reason for this result has been explained above, regardless of the value passed in. What is the original type of the parameters? After one(*x) receives these incoming parameters at the *x position, it will save them as a "tuple", and the tuple cannot be changed

Let's look at a few examples :

#!/usr/bin/env python
#coding=utf-8
#--------
def one(*x):
  """打印出传入参数"""
  for a in x:
    print(a)
lst=["abc",123,"www.pythontab.com"]
stri="abcd"
dect={1:"one",2:"two",3:"three"}
one(*lst)
one(*stri)
one(*dect)


#Program output

abc
123
www.pythontab.com
a
b
c
d
1
2
3


#The first two calls are easy to understand. Finally, we passed in a dictionary element and found that only the key of the dictionary element was output. It does not contain a value. In fact, a single asterisk cannot read the value in the dictionary. It will always read the key in the dictionary. If you want to read the value in the dictionary, you need to use double asterisk

三, double asterisk variable example

At the end of section 2, we used a single asterisk to split a dictionary and pass it to the function, but we could only get the keys of the dictionary. Here is a demonstration of how to use double asterisks to get the value of the dictionary:

#!/usr/bin/env python
#coding=utf-8
#--------
def one(**x):
  """将传入的关键字参数的值保存成元组输出"""
  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)


#Using a double asterisk prefix for a dictionary is equivalent to splitting it into keyword parameters. **dect is equivalent to dividing The dictionary is split into something like this

one=1, two=2, three=3


# Passing the above keyword parameters into one(**x) is equivalent to (remember the previous That said, double asterisk will save all received keyword parameters into a dictionary)

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


# Since it is a dictionary, all methods in the dictionary can be used. Use a for loop to traverse the keys of the dictionary, then use a tuple to add the values ​​corresponding to these keys, and finally print out the tuple

Ps: Note, use this When passing a dictionary into a function in this way, the naming of the dictionary keys must comply with the naming rules of python variables. It is not difficult to see from the above analysis that the double asterisk will first convert the dictionary into the form of keyword parameters, which is equivalent to using The keys in the dictionary are used as variable names. If the key does not comply with the variable naming rules, a "TypeError" exception will be thrown. You can try to reverse the keys and values ​​in the dictionary above and use numbers as keys to see what happens. question.

在一个函数的接收参数中,同时出现"非关键字参数(位置参数)"和"关键字参数"时,可以使用一个单星号来分隔这两种参数,例如:

#!/usr/bin/env python
#coding=utf-8
#--------
def mix(a,b,*,x,y):
  """位置参数与关键字参数混合"""
  return a,b,x,y
#星号前面的a和b是位置参数,星号后面的x和y是关键字参数,调用mix()函数并传入参数时,关键字参数一定要使用"变量名=值"的形式传入数据,如果同位置参数一样传入数据,就会引发一个TypeError异常
print(mix(1,2,x=3,y=4))

   


#程序输出

(1, 2, 3, 4)


#在上面的mix函数中,如果位置参数与关键字参数之间已经存在了一个单星号位置参数,那么,这个参数后面的就都是关键字参数,也不需要再使用星号来分隔他们了,例如

#!/usr/bin/env python
#coding=utf-8
#--------
def mix(a,b,*c,x,y):
  """位置参数与关键字参数混合"""
  return a,b,c,x,y
#在*c的位置可以输入任意多个位置参数值
print(mix(1,2,3,4,5,x=6,y=7))

   

 

#程序输出

(1, 2, (3, 4, 5), 6, 7)

   

如果我们要在一个函数中包含多种参数的组合,必须遵守这样的顺序:位置参数(必选参数),默认参数,单星号参数或星号分隔符,关键字参数,双星号参数;

请看下面的实例:

#!/usr/bin/env python
#coding=utf-8
#--------
def mix(a,b=0,*c,x,**y):
  """位置参数与关键字参数混合"""
  return a,b,c,x,y
print(mix(1,2,3,4,5,x=6,y=7,z=8))

   

#程序输出

(1, 2, (3, 4, 5), 6, {'y': 7, 'z': 8})

   


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)