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

posted on 2018-04-11 10:09  math98  阅读(1026)  评论(0)    收藏  举报