Python methods for removing repeating elements in a list

Source: Internet
Author: User
This example describes how Python removes repeating elements from a list. Share to everyone for your reference. Specific as follows:

It's easier to remember with built-in set

L1 = [' B ', ' C ', ' d ', ' B ', ' C ', ' A ', ' a ']L2 = List (set (L1)) print L2

There is also a speed difference that is said to be faster and not tested.

L1 = [' B ', ' C ', ' d ', ' B ', ' C ', ' A ', ' a ']l2 = {}.fromkeys (L1). Keys () Print L2

Both have a drawback, and the sorting changes after removing the repeating elements:

[' A ', ' C ', ' B ', ' d ']

If you want to keep their original sort:

Using the Sort method of the list class

L1 = [' B ', ' C ', ' d ', ' B ', ' C ', ' A ', ' a ']L2 = List (set (L1)) L2.sort (key=l1.index) Print L2

Can also be written like this

L1 = [' B ', ' C ', ' d ', ' B ', ' C ', ' A ', ' a ']l2 = sorted (set (L1), key=l1.index) print L2

You can also use traverse

L1 = [' B ', ' C ', ' d ', ' B ', ' C ', ' A ', ' a ']l2 = []for i in L1:  if not I in L2:    l2.append (i) Print L2

The code above can also be written like this

L1 = [' B ', ' C ', ' d ', ' B ', ' C ', ' A ', ' a ']L2 = [][l2.append (i) for I in L1 if not I in L2]print L2

This will ensure that the sort is unchanged:

[' B ', ' C ', ' d ', ' a ']

Hopefully this article will help you with Python programming.

  • 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.