"Python" removes problems caused by multiple elements of an array
#-*-coding:utf-8-*-arr=[1,2,3]; For a in Arr:if a<3:arr.remove (a); Print arr;
I wanted to delete the array of less than 3 elements in arr, using the Automatically encapsulated remove () method in the array.
This method removes the single element in the array without any problem, but if you want to delete arr, fewer than 3 element problems come.
There are three elements in arr, with 3 elements of less than 2, and it is clear that after deletion it is only [3], and I start to think so, but the result is [2,3], as shown:
The reason is this:
Remove () When deleting an array of individual elements, it is clear that the pointer position must be shifted forward by 1 bits, which occurs as shown by the pointer offset.
So when you need to delete more than one element in an array, you must never write to the above.
To do this, you can use the following way to end, the array of multiple elements of the deletion, the first copy of this array, delete the time, iterate through the temporary array, delete the elements of the element array, delete the temporary array, this will not occur due to the deletion of the pointer offset. The specific code is as follows:
#-*-coding:utf-8-*-arr=[1,2,3]; arr_temp=arr[:] #直接创建一个新的数组arr_temp并将arr的元素倒进来, Arr_temp=arr, arr_temp is just a pointer to an array of arr. For a in Arr_temp:if a<3:arr.remove (a); Del Arr_temp; Print arr;
The result of the operation is naturally the same as we imagined, with the remaining 3 of this element in arr!
Prevents pointer offsets when an array is removed from an element