Python对list列表结构中的值进行去重的方法总结

yipeiwu_com6年前Python基础

今天遇到一个问题,在同事随意的提示下,用了 itertools.groupby 这个函数。不过这个东西最终还是没用上。
问题就是对一个list中的新闻id进行去重,去重之后要保证顺序不变。
直观方法
最简单的思路就是:

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

相关文章

Python turtle画图库&&画姓名实例

Python turtle画图库&&画姓名实例

*****看一下我定义的change()和run()函数****** 绘图坐标体系: 作用:设置主窗体的大小和位置 turtle.setup(width, height, sta...

python pands实现execl转csv 并修改csv指定列的方法

如下所示: # -*- coding: utf-8 -*- import os import pandas as pd import numpy as np #from os im...

Python入门_浅谈逻辑判断与运算符

Python入门_浅谈逻辑判断与运算符

这是关于Python的第6篇文章,主要介绍下逻辑判断与运算符。 (一) 逻辑判断: 如果要实现一个复杂的功能程序,逻辑判断必不可少。逻辑判断的最基本标准:布尔类型。 布尔类型只有两个值:...

Python机器学习算法库scikit-learn学习之决策树实现方法详解

Python机器学习算法库scikit-learn学习之决策树实现方法详解

本文实例讲述了Python机器学习算法库scikit-learn学习之决策树实现方法。分享给大家供大家参考,具体如下: 决策树 决策树(DTs)是一种用于分类和回归的非参数监督学习方法。...

浅谈Python中的私有变量

私有变量表示方法 在变量前加上两个下划线的是私有变量。 class Teacher(): def __init__(self,name,level): self.__na...