list去重
在进行list去重之前,我们先来学习一下dict的key值和value值的遍历操作。
1、dict的key值遍历定义一个字典,如下:dict1 = {1:"jack",2:"cindy",3:"ruby"}
2、 dict的value值遍历>>> for val in dict1.keys(): ... print val, ... 1 2 3
list去重方法很多,但是效率最高,也最具技巧的算通过dict的key值唯一性,进行去重操作。#方法一: >>> for val in dict1.values(): ... print val, ... jack cindy ruby #方法二: >>> for val in dict1.keys(): ... print dict1[val], ... jack cindy ruby
方法一:通过dict内嵌函数dict.fromkeys(seq, var=None)直接将序列seq生成新的键值不重复的dict对象#coding=utf-8 def listP(list_old): list_new = [] dict_new = {} dict_new = dict.fromkeys(list_old,1) #调用dict内嵌函数生成新的dict对象 #将dict的key值直接转成list list_new = list(dict_new.keys()) return list_new list_old = [1,12,2,2,3,3,5,6] print "old_list:" for i in list_old: print i, list_result = [] list_result = listP(list_old) print "\nnew_list:" for i in list_result: print i,
方法二:通过遍历需要排重的list,将list元素挨个追加到dict中执行结果:#coding=utf-8 def listP(list_old): j = 1 list_new = [] dict = {} for i in list_old: #遍历list,并将元素追加到dict中 dict[i] = j for k in dict.keys(): list_new.append(k) return list_new list_old = [1,12,2,2,3,3,5,6] print "old_list:" for i in list_old: print i, list_result = [] list_result = listP(list_old) print "\nnew_list:" for i in list_result: print i,
整体的思路:old_list: 1 12 2 2 3 3 5 6 new_list: 1 2 3 5 6 12
首先通过将list的元素作为字典的key值存放到字典中,因为字典的key值是不能重复的,所以就起到去重的效果。然后再把字典中的key值取出,存放到一个新的list,这个新的list就是去重后的新list。2、利用list本身的方法去重执行结果:#coding=utf-8 def listP(list_old): list_new = [] for i in list_old: if list_old.count(i) > 1: list_old.remove(i) return list_old list_old = [1,2,3,3,4,6,4,7,1] print "old_list:\n" for i in list_old: print i, list_result = listP(list_old) print "\nnew_list:" for i in list_result: print i,
old_list: 1 2 3 3 4 6 4 7 1 new_list: 2 3 6 4 7 1
Python中list去重
最新推荐文章于 2024-05-27 09:13:02 发布