Several ways to remove the list in Python for Python common face question

Source: Internet
Author: User

In the interview process of the Python-related position, the list of lists will be inspected. (Note that it is sometimes required to ensure that the order of the heavy )

1. Intuitive method

1 li=[1,2,3,4,5,1,2,3]2 new_li=[]3 for in Li:  4     if not in new_li:5        new_ Li.append (i)6print(new_li)

First create a new empty list, by traversing the original list, and then using the logical relationship not in to come and go heavy.

Summary: This can be done, but the process is not simple enough. However, this method guarantees the order of the list.

2, the use of Set automatic weight function

1 li=[1,2,3,4,5,1,2,3]2 li=list (set (LI))3print(LI)

Convert a list to a collection and convert it to a list, taking advantage of the auto-redo function of the collection. Simple and fast. The disadvantage is that using the Set method does not guarantee the order of the go-back.

However, you can ensure that the order of the de-weight is unchanged by using the index method in the list.

1 li=[1,2,3,4,5,1,2,3]2 new_li=list (set (LI))3 new_li.sort (key=  Li.index)4print(new_li)

The above two list de-weight methods are commonly used to go to the weight of the method, it should be noted that the interview if the order to ensure the list, note that the set method through the index can also guarantee the order.

Several ways to remove the list in Python for Python common face question

Related Article

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.