Given a list, the duplicate elements in the list are required to be deleted.
listA = ['python','language','Word','yes','one','Door','move','state','language','Word']
Method 1
Sort the list calls, compare two adjacent elements in sequence from the end, and delete them when encountering duplicate elements. Otherwise, the pointer is moved one by one to the left and repeated the above process:
def deleteDuplicatedElementFromList(list): (); print("sorted list:%s" % list) length = len(list) lastItem = list[length - 1] for i in range(length - 2,-1,-1): currentItem = list[i] if currentItem == lastItem: (currentItem) else: lastItem = currentItem return list
Method 2
Suppose a temporary list saves the results and traverses the original list from the beginning. If there is no current element in the temporary list, add it:
def deleteDuplicatedElementFromList2(list): resultList = [] for item in list: if not item in resultList: (item) return resultList
Method 3
Taking advantage of the uniqueness of collection elements in python, convert the list into a collection and return to the list:
def deleteDuplicatedElementFromList3(listA): #return list(set(listA)) return sorted(set(listA), key = )
Execution results:
print(deleteDuplicatedElementFromList(listA)) #sorted list:['python', 'one', 'move', 'state', 'yes', 'word', 'word', 'word', 'word', 'door']#['python', 'one', 'movement', 'state', 'yes', 'word', 'word', 'door']#No one answers the questions encountered during study? The editor has created a Python learning exchange group: 531509025print(deleteDuplicatedElementFromList2(listA)) #['python', 'verbal', 'verbal', 'yes', 'one', 'door', 'move', 'state'] print(deleteDuplicatedElementFromList3(listA)) #['python', 'verbal', 'verbal', 'yes', 'one', 'door', 'move', 'state']
Summarize:
Method 1, the logic is complex, the temporary variable saves the value to consume memory, the return result destroys the original list order, the worst efficiency
Method 2: Directly call the append method to modify the list in its original place, the logic is clear, and the efficiency is second.
Method 3, extremely concise, the most efficient use of python native methods
This is the end of this article about three ways to delete duplicate elements in the python list. For more related python list, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!