current position:Home>Python series tutorial 127 -- Reference vs copy
Python series tutorial 127 -- Reference vs copy
2022-01-31 23:38:23 【AI technology of artificial intelligence】
friends , If you need to reprint, please indicate the source :blog.csdn.net/jiangjunsho…
Statement : During the teaching of artificial intelligence technology , Many students mentioned to me python Related issues , So in order to let the students master more extended knowledge and better understand AI technology , I put the assistant in charge of sharing this python Series of tutorials , I hope that helps ! Because of this python The tutorial wasn't written by me , So it's not as good as mine AI Technology teaching is humorous , It's boring to learn ; But its knowledge is in place , It's also worth reading !PS: If you don't understand this article, please read the previous article first , Step by step, learn a little everyday, and you won't find it difficult !
We have mentioned , An assignment is a reference to a stored object , Not copies of these objects . Because the assignment operation will produce multiple references to an object , Modifying an object may affect other references to the object elsewhere in the program . If you don't want to change it all , Then you need to tell Python Copy the object , Instead of simply assigning values .
for example , The following example creates a list X, And another list L,L Nested pair list X References to . In addition, a dictionary has been created D, Contains another pair list X References to .
>>> X = [1,2,3]
>>> L = ['a',X,'b'] # Embed references to X's object
>>> D = {'x':X,'y':2}
Copy code
In the code above , There are three references to the same object list :X、L The second element of and D The first element of .
Because of the variable X The list of references is also being L and D Quote inside , Because the list is variable , Modify any of the three references to the list object , It will also change the other two referenced objects at the same time .
>>> X[1] = 'surprise' # Changes all three references!
>>> L
['a',[1,'surprise',3],'b']
>>> D
{'x': [1,'surprise',3],'y': 2}
Copy code
Most of the time , This feature of reference is beneficial to us , Because you can pass large objects anywhere within the program without having to make copies on the way , thus , It can save memory and improve running speed . However , If you don't want this one change all feature , Then you need to explicitly copy .
• Slicing expressions without constraints (L[:]) Able to copy sequences . • Dictionaries copy Method (X.copy()) Be able to copy dictionaries . • Some built-in functions ( for example ,list) Can also generate copies (list(L)).
for instance , If you have a list and a dictionary , You don't want to change their values through other variable references .
>>> L = [1,2,3]
>>> D = {'a':1,'b':2}
Copy code
You can assign copies to other variables , Instead of copying by reference .
>>> A = L[:] # Instead of A = L (or list(L))
>>> B = D.copy() # Instead of B = D (ditto for sets)
Copy code
thus , Changes made by other variables only modify the copy , Not the original object .
>>> A[1] = 'Ni'
>>> B['c'] = 'spam'
>>>
>>> L,D
([1,2,3],{'a': 1,'b': 2})
>>> A,B
([1,'Ni',3],{'a': 1,'c': 'spam','b': 2})
Copy code
For the example at the beginning of the article , You can avoid references by slicing the original list .
>>> X = [1,2,3]
>>> L = ['a',X[:],'b'] # Embed copies of X's object
>>> D = {'x':X[:],'y':2}
Copy code
L and D Now it will point to a different list instead of X. thus , adopt X The changes made can only affect X Without affecting L and D. Similarly , modify L or D It won't affect X.
It should be noted that : Partition of unconditional values and Dictionary copy Method can only do top-level replication . in other words , Nested data structures cannot be copied . If you need to make a complete copy of a deeply nested data structure , Then use the standard copy modular —— First import copy, And then execute X = copy.deepcopy(Y) To any nested object Y Make a complete copy . This call statement can recursively traverse objects to copy all their components .
copyright notice
author[AI technology of artificial intelligence],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201312338220230.html
The sidebar is recommended
- leetcode 1560. Most Visited Sector in a Circular Track(python)
- leetcode 1995. Count Special Quadruplets(python)
- How to program based on interfaces using Python
- leetcode 1286. Iterator for Combination(python)
- leetcode 1418. Display Table of Food Orders in a Restaurant (python)
- Python Matplotlib drawing histogram
- Python development foundation summary (VII) database + FTP + character coding + source code security
- Python modular package management and import mechanism
- Django serialization (II)
- Python dataloader error "dataloader worker (PID XXX) is killed by signal" solution
guess what you like
-
apache2. 4 + Django + windows 10 Automated Deployment
-
leetcode 1222. Queens That Can Attack the King(python)
-
leetcode 1387. Sort Integers by The Power Value (python)
-
Tiger sniffing 24-hour praise device, a case with a crawler skill, python crawler lesson 7-9
-
Python object oriented programming 01: introduction classes and objects
-
Baidu Post: high definition Python
-
Python Matplotlib drawing contour map
-
Python crawler actual combat, requests module, python realizes IMDB movie top data visualization
-
Python classic: explain programming and development from simple to deep and step by step
-
Python implements URL availability monitoring and instant push
Random recommended
- Python avatar animation, come and generate your own animation avatar
- leetcode 1884. Egg Drop With 2 Eggs and N Floors(python)
- leetcode 1910. Remove All Occurrences of a Substring(python)
- Python and binary
- First acquaintance with Python class
- [Python data collection] scrapy book acquisition and coding analysis
- Python crawler from introduction to mastery (IV) extracting information from web pages
- Python crawler from entry to mastery (III) implementation of simple crawler
- The apscheduler module in Python implements scheduled tasks
- 1379. Find the same node in the cloned binary tree (Java / C + + / Python)
- Python connects redis, singleton and thread pool, and resolves problems encountered
- Python from 0 to 1 (day 11) - Python data application 1
- Python bisect module
- Python + OpenGL realizes real-time interactive writing on blocks with B-spline curves
- Use the properties of Python VTK implicit functions to select and cut data
- Learn these 10000 passages and become a humorous person in the IT workplace. Python crawler lessons 8-9
- leetcode 986. Interval List Intersections(python)
- leetcode 1860. Incremental Memory Leak(python)
- How to teach yourself Python? How long will it take?
- Python Matplotlib drawing pie chart
- Django paging (II)
- Concurrent. For Python concurrent programming Futures or multiprocessing?
- Programmers over the age of 25 can't know a few Chinese herbal medicines. Python crawler lessons 9-9
- Python crawler from introduction to pit full series of tutorials (detailed tutorial + various practical combat)
- The second bullet of class in Python
- Python object oriented programming 03: class inheritance and its derived terms
- How IOS developers learn Python Programming 13 - function 4
- Python crawler from introduction to mastery (VI) form and crawler login
- Python crawler from entry to mastery (V) challenges of dynamic web pages
- Deeply understand pandas to read excel, TXT, CSV files and other commands
- Daily python, Chapter 18, class
- "I just want to collect some plain photos in Python for machine learning," he said. "I believe you a ghost!"
- Django view
- Python implements filtering emoticons in text
- When winter comes, python chooses a coat with temperament for mom! Otherwise, there's really no way to start!
- Python crawler - get fund change information
- Highlight actor using Python VTK
- Python crawler actual combat: crawling southern weekend news articles
- leetcode 406. Queue Reconstruction by Height(python)
- leetcode 1043. Partition Array for Maximum Sum (python)