search
HomeBackend DevelopmentPython TutorialIntroduction to several 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 variables " to realize 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, the asterisk variable is used to pass the parameters of the function. In the following example, a single asterisk represents This position receives any number of non-keyword parameters and converts them into tuples at the *b position of the function. The double asterisk indicates that this position receives any number of keyword parameters and converts them 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 to the *b position, and *b will Convert these incoming parameters into a tuple, and the following call

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

#pass in one(a,*b) Finally, 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)

#pass 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 make this variable Split 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 call of one(stri,lst) is equivalent to one(*x) after substitution With

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

#The second call to one( *lst), after substituting one(*x), it is equivalent to

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

#the third time Calling one(*stri) and substituting one(*x) 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. The individual elements in the variable are disassembled and then passed into the one() function in turn. After passing in the one() function, The one() function will save these incoming single elements as a tuple, which is why we print(x[0]) can extract the first element

In order to verify this, we modify Take a look at 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 split the list and pass it into the one() function, and try to change the value of the first element inside the function. The result The "TypeError" exception is triggered. You can try it yourself. The reason for this result has been explained above. No matter what the original type of the incoming parameters is, one(*x) receives these incoming parameters at the position of *x. Afterwards, it will be saved 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
#Previous Both calls are easy to understand. Finally, we passed in a dictionary element and found that only the key of the dictionary element was output and did not contain the value. In fact, a single asterisk cannot read the value in the dictionary. It will always only The keys in the dictionary will be read. If you want to read the values ​​in the dictionary, you need to use double asterisks

3. Double asterisk variable examples

At the end of section 2, we use A single asterisk splits a dictionary and passes it to the function, but only the keys of the dictionary can be obtained. The following demonstrates how to use double asterisks to obtain the values ​​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 on a dictionary is equivalent to splitting it into the form of keyword parameters. **dect is equivalent to splitting the dictionary into the following form

one=1,two=2, three=3

#将上面这些关键字参数传入one(**x),就等价与(还记得前面说的,双星号将接收到的所有关键字参数都保存成一个字典吧)

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

#既然是字典,那么字典中的所有方法都能使用,使用for循环遍历这个字典的键,然后使用一个元组来添加这些键对应的值,最后打印出这个元组

Ps:注意,使用这种方法将字典传入函数的时候,字典的键的命名要符合python变量的命名规则,通过上面的分析也不难看出,双星号会将字典首先转换成关键字参数的形式,就相当于使用字典中的键作为变量名,如果键不符合变量命名规则,则会抛出一个"TypeError"异常,大家可以尝试着颠倒一下上面字典中的键和值,使用数字作为键,看看会出现什么问题。

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

#!/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})

The above is the detailed content of Introduction to several special uses of asterisk variables in Python. For more information, please follow other related articles on the PHP Chinese website!

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
The Main Purpose of Python: Flexibility and Ease of UseThe Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AM

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python: The Power of Versatile ProgrammingPython: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Learning Python in 2 Hours a Day: A Practical GuideLearning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AM

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

Python vs. C  : Pros and Cons for DevelopersPython vs. C : Pros and Cons for DevelopersApr 17, 2025 am 12:04 AM

Python is suitable for rapid development and data processing, while C is suitable for high performance and underlying control. 1) Python is easy to use, with concise syntax, and is suitable for data science and web development. 2) C has high performance and accurate control, and is often used in gaming and system programming.

Python: Time Commitment and Learning PacePython: Time Commitment and Learning PaceApr 17, 2025 am 12:03 AM

The time required to learn Python varies from person to person, mainly influenced by previous programming experience, learning motivation, learning resources and methods, and learning rhythm. Set realistic learning goals and learn best through practical projects.

Python: Automation, Scripting, and Task ManagementPython: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment