python 去重

  1. def func1(one_list):  
  2.     ''''' 
  3.     使用集合,个人最常用 
  4.     '''  
  5.     return list(set(one_list))  
  6.   
  7.   
  8. def func2(one_list):  
  9.     ''''' 
  10.     使用字典的方式 
  11.     '''  
  12.     return {}.fromkeys(one_list).keys()  
  13.   
  14.   
  15. def func3(one_list):  
  16.     ''''' 
  17.     使用列表推导的方式 
  18.     '''  
  19.     temp_list=[]  
  20.     for one in one_list:  
  21.         if one not in temp_list:  
  22.             temp_list.append(one)  
  23.     return temp_list  
  24.   
  25.   
  26. def func4(one_list):  
  27.     ''''' 
  28.     使用排序的方法 
  29.     '''  
  30.     result_list=[]  
  31.     temp_list=sorted(one_list)  
  32.     i=0  
  33.     while i<len(temp_list):  
  34.         if temp_list[i] not in result_list:  
  35.             result_list.append(temp_list[i])  
  36.         else:  
  37.             i+=1  
  38.     return result_list  
  39.   
  40.   
  41. if __name__ == '__main__':  
  42.     one_list=[56,7,4,23,56,9,0,56,12,3,56,34,45,5,6,56]  
  43.     print func1(one_list)  
  44.     print func2(one_list)  
  45.     print func3(one_list)  
  46.     print func4(one_list) 

结果:

  1. [0, 34, 3, 4, 5, 6, 7, 9, 12, 45, 23, 56]  
  2. [0, 34, 3, 4, 5, 6, 7, 9, 12, 45, 23, 56]  
  3. [56, 7, 4, 23, 9, 0, 12, 3, 34, 45, 5, 6]  
  4. [0, 3, 4, 5, 6, 7, 9, 12, 23, 34, 45, 56]  


猜你喜欢

转载自blog.csdn.net/sun_daming/article/details/80563701
今日推荐