python中list中的元素去重

 

直观方法

最简单的思路就是:

 

代码如下:

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

另外一个解决方案就是用set:

代码如下:

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

这样的结果是没有保持原来的顺序。

 

按照索引再次排序

最后通过这种方式解决:

代码如下:

ids = [1,4,3,3,4,2,3,4,5,6,1]
news_ids = list(set(ids))
news_ids.sort(ids.index)

 

使用itertools.grouby

文章一开始就提到itertools.grouby, 如果不考虑列表顺序的话可用这个:

代码如下:

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的原理可以看这里:http://docs.python.org/2/library/itertools.html#itertools.groupby

网友补充:用reduce

网友reatlk留言给了另外的解决方案。我补充并解释到这里:

代码如下:

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]


上面是我在ipython中运行的代码,其中的 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的特性。reduce解释参看这里:http://docs.python.org/2/library/functions.html#reduce

另外还有一种方法:

使用 collections.OrderedDict.fromkeys()

这是完成特殊任务的最快方式。它首先删除列表中的重复项并返回一个字典,最后将其转换为列表。此方法也可用于字符串,之后列表中元素的顺序也发生了变化。

# Python 3 code to demonstrate 
# removing duplicated from list
# using collections.OrderedDict.fromkeys()
from collections import OrderedDict
# initializing
list
test_list = [1, 5, 3, 6, 3, 5, 6, 1]
print ("The original list is : " + str(test_list))
# using collections.OrderedDict.fromkeys()
# to remove duplicated from list
res = list(OrderedDict.fromkeys(test_list))
# printing list after removal print ("The list after removing duplicates : " + str(res))
 
posted @ 2023-02-13 23:00  海_纳百川  阅读(49)  评论(0编辑  收藏  举报
本站总访问量