Please define the function , Will list [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1] Remove the duplicate elements in , Write at least 3 Methods .
Method 1 : Using sets to duplicate
list_1=[10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]def func1(list_1): return list(set(list_1))print(' The list after de duplication :',func1(list_1))
Method 2 : utilize for loop
list_2 = [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]def func2(list_2): # Define an empty list mylist_2=[] #i Traverse list_2 for i in list_2: # If i be not in mylist_2, Add to mylist_2 if i not in mylist_2: mylist_2.append(i) print(mylist_2)print(func2(list_2))
Method 3 : Skillfully use sort() Sort
list_3 = [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]def func3(list_3): result_list=[] temp_list=sorted(list_3) i=0 while i<len(temp_list): # If not result_list Then add in , otherwise i+1 if temp_list[i] not in result_list: result_list.append(temp_list[i]) else: i+=1 return result_listprint(func3(list_3))
Method four : Using dictionary skillfully
list_4= [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]def func4(list_4): #fromkeys() Function to create a new dictionary , Key to get the new dictionary ( The key value is unique ) result_list = [] for i in {}.fromkeys(list_4).keys(): result_list.append(i) return result_listprint(func4(list_4))
Method five : Using iterators
import itertoolslist_5= [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]def func5(list_5): list_5.sort() temp_list= itertools.groupby(list_5) result_list=[] for i,j in temp_list: result_list.append(i) return result_listprint(func5(list_5))
Running results :
This is about Python That's all for the list de duplication article . I hope it will be helpful for your study , I also hope you can support the software development network .