ids = [1,2,3,3,4,2,3,4,5,6,1] news_ids = [] for id in ids: if id not in news_ids: news_ids.append(id) print news_ids
ids = [1,4,3,3,4,2,3,4,5,6,1] ids = list(set(ids))
import itertools ids = [1,4,3,3,4,2,3,4,5,6,1] ids.sort() it = itertools.groupby(ids) for k, g in it: print k
In [5]: ids = [1,4,3,3,4,2,3,4,5,6,1] In [6]: func = lambda x,y:x if y in x else x + [y] In [7]: reduce(func, [[], ] + ids) Out[7]: [1, 4, 3, 2, 5, 6]
其中的 lambda x,y:x if y in x else x + [y] 等价于 lambda x,y: y in x and x or x+[y] 。
思路其实就是先把ids变为[[], 1,4,3,......] ,而后在利用reduce的特性.html
list2 = [] list1 = [1,2,3,2,2,2,4,6,5] for i in list1: if i not in list2: list2.append(i) list2 [1, 2, 3, 4, 6, 5]
或者使用删除元素索引的方法对列表去重,而且不改变原列表的顺序 # python for删除的时候会往前移(垃圾回收机制),未遍历到的后一个占了前一个被删除的"位置",致使这个数不会被遍历到,而使最后的结果错误 # 局部变量在栈内存中存在,当for循环语句结束,那么变量会及时被gc(垃圾回收器)及时的释放掉,不浪费空间; # 若是使用循环以后还想去访问循环语句中控制那个变量,使用while循环。 # 因此使用while循环删除nums中的Val(的下标) nums = [1,2,3,3,4,2,3,4,5,6,1] val = 3 while val in nums: nums.pop(nums.index(val)) print nums return len(nums)