Python Reverse traversal

Source: Internet
Author: User

This occurs because the list length changes after the pop, and the second pop is the new list,

can be deleted in order from small to large, each deleted, after the index to be deleted minus 1: The first pop (1), the second pop (3-1) ....

The general solution is given here: 1, reverse loop traversal, 2, traverse the copy list, manipulate the original list.

Reverse loop traversal of three methods: http://blog.csdn.net/iflysoft/article/details/9013315

Implementation 1:

Source = ['a','b','C','D','e','F','g','h']#to delete the element with index 2,4,6 in this list, the result should be a B d f hDel_list = [4,6,2]#The index number that will be deleted is assumed to be unordered forIndexinchRange (len (source) -1,-1,-1):#Cycle Order 7 6 5 4 3 2 1 0     forDel_indexinchdel_list:ifindex = =Del_index:source.pop (Index)#In this way, the reverse traversal deletes the largest index in the Del_list, which is the element closest to the tail in source.#As you can see, this is actually the removal step, pop (6) pop (4) pop (2) can also do this:Del_list.sort (Reverse=true)#Del_list Descending Order forIinchDel_list:source.pop (i)Print(source)#either of these two methods is optional

Implementation 2:

It's just a different way of walking backwards, using the way the list slices, (strings can also be sliced)

Source = ['a','b','C','D','e','F','g','h'] forIinchSOURCE[::-1]:#list Slice, which is creating a new list that may consume memory    Print(i)#H G F E D c B a forIinchReversed (source):#reverses the list and creates a new list    Print(i)#H G F E D c B a

Python Reverse traversal

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.