本文實例講述了Python實現去除列表中重復元素的方法。分享給大家供大家參考,具體如下:
這里一共使用了四種方法來去除列表中的重復元素,下面是具體實現:
#!usr/bin/env python#encoding:utf-8'''__Author__:沂水寒城功能:去除列表中的重復元素'''def func1(one_list): ''''' 使用集合,個人最常用 ''' return list(set(one_list))def func2(one_list): ''''' 使用字典的方式 ''' return {}.fromkeys(one_list).keys()def func3(one_list): ''''' 使用列表推導的方式 ''' temp_list=[] for one in one_list: if one not in temp_list: temp_list.append(one) return temp_listdef func4(one_list): ''''' 使用排序的方法 ''' result_list=[] temp_list=sorted(one_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_listif __name__ == '__main__': one_list=[56,7,4,23,56,9,0,56,12,3,56,34,45,5,6,56] print "武林站長站測試結果:" print func1(one_list) print func2(one_list) print func3(one_list) print func4(one_list)結果如下:
武林站長站測試結果:
[0, 34, 3, 4, 5, 6, 7, 9, 12, 45, 23, 56]
[0, 34, 3, 4, 5, 6, 7, 9, 12, 45, 23, 56]
[56, 7, 4, 23, 9, 0, 12, 3, 34, 45, 5, 6]
[0, 3, 4, 5, 6, 7, 9, 12, 23, 34, 45, 56]
運行結果截圖:

PS:本站還有兩款比較簡單實用的在線文本去重復工具,推薦給大家使用:
在線去除重復項工具:
http://tools.jb51.net/code/quchong
在線文本去重復工具:
http://tools.jb51.net/aideddesign/txt_quchong
更多關于Python相關內容可查看本站專題:《Python字典操作技巧匯總》、《Python字符串操作技巧匯總》、《Python常用遍歷技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答