Python removes repeated elements from the list. python removes list elements.

Source: Internet
Author: User

Python removes repeated elements from the list. python removes list elements.

This article describes how to remove repeated elements from the list using Python. Share it with you for your reference. The details are as follows:

The built-in set is easier to remember.

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 never tested.

l1 = ['b','c','d','b','c','a','a']l2 = {}.fromkeys(l1).keys()print l2

Both of them have a disadvantage. Sorting changes after removing duplicate elements:

['a', 'c', 'b', 'd']

If you want to keep their original order:

Use 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

You can also write it like this.

l1 = ['b','c','d','b','c','a','a']l2 = sorted(set(l1),key=l1.index)print l2

You can also use Traversal

l1 = ['b','c','d','b','c','a','a']l2 = []for i in l1:  if not i in l2:    l2.append(i)print l2

The above code 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

In this way, the sorting will not change:

['b', 'c', 'd', 'a']

I hope this article will help you with Python programming.

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.