Python實現去除列表中重複元素的方法

來源:互聯網
上載者:User
這篇文章主要介紹了Python實現去除列表中重複元素的方法,結合執行個體形式總結分析了Python列表去重的4種實現方法,涉及Python針對列表的遍曆、判斷、排序等相關操作技巧,需要的朋友可以參考下

本文執行個體講述了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]

運行結果:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.