Home > Backend Development > Python Tutorial > Three methods to delete duplicate elements in lists and efficiency analysis

Three methods to delete duplicate elements in lists and efficiency analysis

高洛峰
Release: 2016-10-19 17:12:50
Original
1779 people have browsed it

Method 1:

Use the sort() method of the list object to sort the list, loop through the list starting from the last element, and determine whether two adjacent elements are equal!

def methodOne(list):
    list.sort()
    lenList = len(list)
    lastItem = list[lenList-1]
    for i in range(lenList-2,-1,-1):
        if list[i] == lastItem:
            list.remove(list[i])
        else:
            lastItem = list[i]
    return list
Copy after login

Method 2:

Define a temporary list, if the elements iterated by the loop are not in the temporary list, add them, and finally return the temporary list!

def methodTwo(list):
    tempList = []
    for i in list:
        if not i in tempList:
            tempList.append(i)
    return tempList
Copy after login

Method three:

lists=[20,12,34,12,24,34,55,27]
print list(set(lists))
Copy after login

1. Compared with method two, method one has more additional operations such as sorting and assignment. Because in Python, variables are immutable. Every time an element is iterated out and compared, the operation is to create a new local variable and assign a value and discard the original variable, which requires more memory! At the same time, because of the sorting operation, Destroys relative positioning.

2. Method 2 creates a temporary list for operation, and the list is variable. Each time an element is appended, it only adds an index and value to the original list, so it is more efficient than method 1!

3. The third method is undoubtedly the most efficient among the three methods (both in terms of code simplicity and operating efficiency): set() is a built-in data type "set type", which is unordered and the value is the only item. ! Therefore, the result of set() execution is to convert it into a set and directly remove duplicate elements, and then list() will convert the set back to a list type.

However, set() will destroy the sorting order. If you want to preserve the sorting, list(set(lists)) can be changed to sorted(set(lists),key=lists.index)


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template