這篇文章將為大家詳細(xì)講解有關(guān)Python怎么實(shí)現(xiàn)去除列表中重復(fù)元素功能,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
具體如下:
# !/usr/bin/env python # -*- coding:utf-8 -*- ''' __Author__:沂水寒城 功能: python列表去除方法總結(jié)(7種方法) ''' import sys reload(sys) import copy sys.setdefaultencoding("utf-8") from collections import Counter def func1(data_list): ''' 使用內(nèi)置set方法去重 ''' return list(set(data_list)) def func2(data_list): ''' 借助字典方法fromkeys ''' return list({}.fromkeys(data_list).keys()) def func3(data_list): ''' 使用類列表推導(dǎo)式 ''' res_list=[] for one in data_list: if not one in res_list: res_list.append(one) return res_list def func4(data_list): ''' 使用sorted函數(shù)(其實(shí)本質(zhì)上還是使用set方法進(jìn)行的排序) ''' res_list=copy.deepcopy(data_list) res_list=sorted(set(data_list),key=data_list.index) return res_list def func5(data_list): ''' 使用"排序+計(jì)數(shù)"的方法 ''' result_list=[] temp_list=sorted(data_list) i=0 while i<len(temp_list): if temp_list[i] not in result_list: result_list.append(temp_list[i]) else: i+=1 return result_list def flagFunc(a): ''' 布爾函數(shù) ''' if a in count_dict: count_dict[a]+=1 return False else: count_dict[a]=1 return True def func6(data_list): ''' 使用map方法 ''' global count_dict count_dict={} tmp_list=map(flagFunc,data_list) return [data_list[i] for i in range(len(data_list)) if tmp_list[i]] def func7(data_list): ''' 借助collections模塊中的Counter方法(頻度過濾方法) ''' fre_list=Counter(data_list).most_common(len(data_list)) return [one[0] for one in fre_list] if __name__=='__main__': data_list=[12,4,7,3,4,2,4,3,5,12,78,9,0,4,5,0,44,3] print func1(data_list) print func2(data_list) print func3(data_list) print func4(data_list) print func5(data_list) print func6(data_list) print func7(data_list)
結(jié)果如下:
[0, 2, 3, 4, 5, 7, 9, 12, 78, 44]
[0, 2, 3, 4, 5, 7, 9, 12, 78, 44]
[12, 4, 7, 3, 2, 5, 78, 9, 0, 44]
[12, 4, 7, 3, 2, 5, 78, 9, 0, 44]
[0, 2, 3, 4, 5, 7, 9, 12, 44, 78]
[12, 4, 7, 3, 2, 5, 78, 9, 0, 44]
[4, 3, 0, 5, 12, 2, 7, 9, 78, 44]
果然還是很有意思的哈!
關(guān)于“Python怎么實(shí)現(xiàn)去除列表中重復(fù)元素功能”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯(cuò),請把它分享出去讓更多的人看到。
名稱欄目:Python怎么實(shí)現(xiàn)去除列表中重復(fù)元素功能-創(chuàng)新互聯(lián)
網(wǎng)頁路徑:http://aaarwkj.com/article28/dohocp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計(jì)、手機(jī)網(wǎng)站建設(shè)、企業(yè)建站、網(wǎng)站內(nèi)鏈、動態(tài)網(wǎng)站、營銷型網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容