In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "how to solve the Python list trap caused by sequence assignment", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to solve the Python list trap caused by sequence assignment.
+
+ refers to splicing the elements of two sequences together. Usually, the sequences on both sides of the + sign are made up of the same type of data. In the process of splicing, neither of the two operated sequences will be modified. Python will create a new sequence containing the same type of data as the stitching result. For example:
A = [1] b = [2] c = a + b print (a, b, c) print (id (a), id (b), id (c))
The result is:
[1] [2] [1, 2] 2409610524480 2409610523520 2409610523648
*
If you want to make several copies of a sequence and then splice it together, it is quicker to multiply the sequence by an integer. Again, this operation produces a new sequence:
> l = [1] > > l * 5 [1, 1, 1, 1] > 5 * "a" 'aaaaa'
Both + and * follow this rule and do not modify the original operands, but build an entirely new sequence.
List set list trapping
Guess what the result will be:
X = ["x"] my_list = [x] * 3 print (my_list) # [['x'], ['x'], ['x']] x2 = my_list [2] x2 [0] = "y" print (my_list)
To be reasonable, it should be [['x'], ['x'], ['y'], but it is wrong, it is actually:
[['y'], ['y']]
Unbelievable! Assign a value to the list of the last element in my_list, and as a result, the list of all three elements is assigned! This reflects that the three elements of my_list are not three lists, but three list references that point to the same list. Equivalent to:
X = ["x"] my_list = [] for i in range (3): my_list.append (x) # append the same object x2 = my_list [2] x2 [0] = "y" print (my_list) # [['y'], ['y'], ['y']
The same object is appended to my_list each time. If you want to generate three different lists, you need to create a new list in each iteration:
My_list = [] for i in range (3): X = ["x"] # New list my_list.append (x) x2 = my_list [2] x2 [0] = "y" print (my_list) # [['x'], ['x'], ['y']]
This is in line with expectations. You can use list derivation to simplify the code:
X = ["x"] my_list = [x for i range (3)] x2 = my_list [2] x2 [0] = "y" print (my_list) # [['x'], ['x'], ['y']]
Lesson:
Create a new list in the list, use list derivation, and do not use the * operator.
If the elements in the sequence an are references to other mutable objects in the a * n statement, you need to pay special attention to this, which may not be the effect you want.
+ =
Although a + = b means a = a + b, the special method behind it is _ _ iadd__,. If a class does not implement this method, Python will step back to call _ _ add__. The _ _ iadd__ method appends directly to the original object, and the _ _ add__ method creates a new object and then assigns the value.
* =
These concepts of + = also apply to * =, except that the latter corresponds to _ _ imul__. Append or new object, the effect is obvious when acting on variable sequence and immutable sequence, for example:
# variable sequence, append > > l = [1,2,3] > id (l) 2135319475136 > > l * = 2 > l [1,2,3,1,2,3] > > id (l) 2135319475136 # id is the same # immutable sequence, new object > t = (1,2,3) > id (t) 2135322139520 > > t * = 2 > id (t) 2135321695424 # id is different
The trapping of tuple set list
> t = (1,2, [30,40]) > t [2] + = [50,60]
Guess which of the following four situations will happen? A. t becomes (1, 2, [30, 40, 50, 60]) b. Because tuple does not support assigning values to its elements, the TypeError exception c. Neither of the above is d.an and b is right because tuples cannot be assigned, so I will not hesitate to choose b. But in fact, the answer is that both Dempa and b are right, and they will not only succeed in assigning values, but also report errors:
> t = (1,2, [30,40]) > > t [2] + = [50,60] Traceback (most recent call last): File ", line 1, in TypeError: 'tuple' object does not support item assignment > t (1,2, [30,40,50,60])
Oh No! Why? First, the assignment is successful, because t [2] points to a mutable object (list [30,40]), which can be assigned. Second, an error is reported, because the variable object is assigned to the immutable object (tuple t), and the immutable object cannot be assigned.
Write t [2] .extend ([50,60]) to avoid this exception.
Lesson:
Do not put mutable objects in tuples.
+ = is not an atomic operation, and although an exception was thrown, the operation was completed.
The Brazilian author says that in his 15-year Python career, he has never seen anyone suffer in this place.
At this point, I believe you have a deeper understanding of "how to solve the Python list trap caused by sequence assignment". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.