Prevents pointer offsets when an array is removed from an element

Source: Internet
Author: User
"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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.