python中对list去重的多种方法

怎么快速的对列表进行去重呢,去重之后原来的顺序会不会改变呢?

1.以下的几种情况结果是一样的,去重之后顺序会改变:

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

或用set

ids = [1,4,3,3,4,2,3,4,5,6,1]
ids = list(set(ids))

或使用itertools.grouby

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

关于itertools.groupby的原理可以看这里:(1) http://docs.python.org/2/library/itertools.html#itertools.groupby

(2) https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001415616001996f6b32d80b6454caca3d33c965a07611f000

2.怎么能不改变原来的顺序呢?(要用到reduce 关于reduce的介绍  http://docs.python.org/2/library/functions.html#reduce)

关于lambda的文章:http://www.cnblogs.com/nyist-xsk/p/7404675.html

关于reduce的文章: (1) http://www.cnblogs.com/XXCXY/p/5180245.html

(2) http://www.pythoner.com/46.html

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的特性.

去列表去重,不改变原来的顺序,还可以使用一个空列表把原列表里面不重复的数据"装起来",例如:

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)

原文地址:https://www.cnblogs.com/nyist-xsk/p/7473236.html