Python deconstruction and packaging

Python deconstruction and packaging#

Ask a question##

First look at the following code

x =1
y =2

tmp = x
x = y
y = tmp

print(x, y)

The output of the code is: 2 1

Look at the following code:

x =1
y =2

x, y = y, x
print(x, y)

The output of the code is: 2 1

x, y = y, xThe meaning behind this code is deconstruction and encapsulation

Python package##

In [1]: t =1,2

In [2]: t
Out[2]:(1,2)

In [3]:type(t)
Out[3]: tuple			#The parentheses can be omitted when defining tuples

In [4]: t1 =(1,2)

In [5]: t2 =1,2
						#t1 and t2 are equivalent
In [6]: t1
Out[6]:(1,2)

In [7]: t2
Out[7]:(1,2)

So the result of encapsulation must be a tuple.

x, y = y, xThe right side of this code will be encapsulated as (y, x)

Python Deconstruction##

Basic Deconstruction###

In [8]: lst =[1,2]

In [9]: first, second = lst

In [10]:print(first, second)12

According to the order of the elements, assign the elements of the linear structure lst to the variables first, second

Add an asterisk to deconstruct###

In [11]: lst =list(range(5))

In [12]: head,*tail = lst

In [13]: head
Out[13]:0

In [14]: tail
Out[14]:[1,2,3,4]

In [15]:*lst2 = lst	#There must be an asterisked variable on the left
 File "<ipython-input-15-98211a44ccfb>", line 1*lst2 = lst
               ^
SyntaxError: starred assignment target must be in a list or tuple

In [16]:*head, tail = lst

In [17]: head
Out[17]:[0,1,2,3]

In [18]: lst
Out[18]:[0,1,2,3,4]

In [19]: tail
Out[19]:4

In [20]: head,*m1,*m2, tail = lst		#There cannot be multiple asterisks, only one
 File "<ipython-input-20-1fc1a52caa8e>", line 1
 head,*m1,*m2, tail = lst
                              ^
SyntaxError: two starred expressions in assignment

In [21]: v1, v2, v3, v4, v5, v6, v7 = lst	#The number of variables on the left cannot exceed the number of elements on the right
---------------------------------------------------------------------------
ValueError                                Traceback(most recent call last)<ipython-input-21-9366cfb498a1>in<module>()---->1 v1, v2, v3, v4, v5, v6, v7 = lst

ValueError: not enough values to unpack(expected 7, got 5)

In [22]: v1, v2 = lst						#The number of variables on the left cannot be less than the number of elements on the right
---------------------------------------------------------------------------
ValueError                                Traceback(most recent call last)<ipython-input-22-d7b0a4e7871e>in<module>()---->1 v1, v2 = lst

ValueError: too many values to unpack(expected 2)

Summarized as the following rules:

Multi-level deconstruction###

Deconstruction supports multiple levels

In [23]: lst =[1,(2,3),5]

In [24]: _, v,*_ = lst		#v resolves to(2,3)

In [25]: v
Out[25]:(2,3)

In [26]: _, val = v			#v can be further deconstructed

In [27]: val
Out[27]:3

In [28]: _,(_, val),*_ = lst		#Can be deconstructed in one step

In [29]: val
Out[29]:3

In [30]: _,[*_, val],*_ = lst		#Deconstruct the middle part into a list

In [31]: val
Out[31]:3

In [32]: _, _, val,*_ = lst		# (2,3)Resolve to the second_

In [33]: val
Out[33]:5

The use of Python underscore###

Using a single underscore _ means discarding the variable, which is a Python convention. A single underscore is also a valid identifier in Python, but if you don't want to discard a variable, you usually don't use a single underscore to indicate a meaningful variable. It can be understood as a convention.

Use of Deconstruction and Encapsulation###

Very complex data structure, multi-layer nested linear structure, you can use deconstruction to quickly extract the value, which is very convenient

For example, the following method of use

In [1]: key, _, value ='I love Python'.partition(' love ')

In [2]: key
Out[2]:'I'

In [3]: value
Out[3]:'Python'

Recommended Posts

Python deconstruction and packaging
Python and Go
Python introspection and reflection
[python] python2 and python3 under ubuntu
Python3 configuration and entry.md
Python automated operation and maintenance 2
Python introduction and environment installation
Python know crawler and anti crawler
centos7 install python3 and ipython
ubuntu18.04 compile and install python3.8
Centos 6.10 reinstall python and yum
Python open read and write
CentOS7 install python3 and pip3
Python automated operation and maintenance 1
Python data structure and algorithm
Python multi-process and multi-thread basics
CentOS 6.9 compile and install python
CentOS 6 compile and install python 3
Generators and iterators in Python
Python file read and write operations
Python and js interactive call method
Magic methods and uses of Python
Python judges positive and negative numbers
python ftp upload files and folders
Python crawler | Cognitive crawler request and response
FM algorithm analysis and Python implementation
Common errors and solutions in python
Python function definition and parameter explanation
CentOS quickly install Python3 and pip3
Mongodb and python interaction of python crawler
Install Python3 and ansible under CentOS8
Python processing PDF and CDF examples
Played with stocks and learned Python
Configure python3 environment on centos7 and
Python reads and writes json files
Python implements username and password verification
Install Python3 and Py under CentOS7
Python basic syntax and number types
Python learning os module and usage
Python process and thread summary case analysis
How to use and and or in Python
Python tricks and tricks-continue to be updated...
Python implementation of intersection and IOU tutorial
Getting started with python-2: functions and dictionaries
Naive Bayes algorithm and its Python implementation
Centos python3 compile installation and compile gcc upgrade
Example of python calculating derivative and plotting
Python and scrapy deployment in centos environment
Python implements singly linked lists and dictionaries
Deploy python3 and nginx projects on ubuntu18.04
How does python distinguish return and yield
Python file and directory operation code summary
Talking about Python multithreading and program lock
Python process and thread summary case analysis