程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Five Python methods for list de duplication

編輯:Python

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved