Will list [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1] Remove duplicate elements .
# 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): """ Using sets to duplicate """ return list(set(list_1)) print(' The list after de duplication :',func1(list_1)) #[1, 2, 3, 10, 44, 15, 20, 56] # Method 2 : use for loop ''' use i Traverse list, If not in the new list , Then add to the new list ,, Otherwise, don't add it in , In turn, cycle ''' list_2 = [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1] def func2(list_2): """ Derivation using list """ # 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) return list_2 print(func2(list_2)) [1, 2, 3, 10, 15, 20, 44, 56] #[1, 2, 3, 10, 44, 15, 20, 56] # Method 3 : Use a list of sort() Methods the sorting , The default is ascending list_3 = [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1] def func3(list_3): """ Use the sort method """ 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_list print(func3(list_3)) #[1, 2, 3, 10, 15, 20, 44, 56] # Method four list_4= [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1] def func4(list_4): """ The way to use a dictionary """ #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_list print(func4(list_4)) #[10, 1, 2, 20, 3, 15, 44, 56] Go from left to right from the original list , So the order is different # Method five # Iterator module import itertools list_5= [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1] def func5(list_5): """ Using iterators """ list_5.sort() temp_list= itertools.groupby(list_5) result_list=[] for i,j in temp_list: result_list.append(i) return result_list print(func5(list_5)) #[1, 2, 3, 10, 15, 20, 44, 56]
ITester Software testing stack (ID:ITestingA), Focus on software testing technology and treasure dry goods sharing , Update original technical articles on time every week , Technical books will be presented irregularly every month , May we meet on a higher level . I like to remember stars , Get the latest push in time every week , Please indicate the source of the third party reprint .
Unittest The framework is intr
Catalog problem Solution Th