Python列表去重的幾種方法整理
更新時間:2022年06月29日 10:18:50 作者:小旭2021
這篇文章介紹了Python列表去重的幾種方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
請定義函數(shù),將列表[10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]中的重復元素除去,寫出至少3種方法。
方法一:利用集合去重
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('去重后的列表:',func1(list_1))
方法二:利用for循環(huán)
list_2 = [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1] def func2(list_2): #定義一個空列表 mylist_2=[] #i遍歷list_2 for i in list_2: #如果i不在mylist_2,則添加到mylist_2 if i not in mylist_2: mylist_2.append(i) print(mylist_2) print(func2(list_2))
方法三:巧用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): #如果不在result_list則添加進去,否則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))
方法四:巧用字典
list_4= [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1] def func4(list_4): #fromkeys() 函數(shù)創(chuàng)建一個新字典,獲取新字典的鍵(鍵值是唯一的) result_list = [] for i in {}.fromkeys(list_4).keys(): result_list.append(i) return result_list print(func4(list_4))
方法五:利用迭代器
import itertools list_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_list print(func5(list_5))
運行結(jié)果:
到此這篇關(guān)于Python列表去重的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
tensorflow卷積神經(jīng)Inception?V3網(wǎng)絡(luò)結(jié)構(gòu)代碼解析
這篇文章主要為大家介紹了卷積神經(jīng)Inception?V3網(wǎng)絡(luò)結(jié)構(gòu)代碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05