• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > python中对list去重的多种方法

python中对list去重的多种方法

作者:junjie 字体:[增加 减小] 来源:互联网

junjie 通过本文主要向大家介绍了python list方法,python tolist方法,python list 去重,python list去重复,python3 list 去重等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

今天遇到一个问题,在同事随意的提示下,用了 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
</div>

这样也可行,但是看起来不够爽。

用set

另外一个解决方案就是用set:
ids = [1,4,3,3,4,2,3,4,5,6,1]
ids = list(set(ids))
</div>
这样的结果是没有保持原来的顺序。

按照索引再次排序

最后通过这种方式解决:
ids = [1,4,3,3,4,2,3,4,5,6,1]
news_ids = list(set(ids))
news_ids.sort(ids.index)
</div>

使用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
</div>

关于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]
</div>
上面是我在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

</div>

您可能想查找下面的文章:

  • python list排序的两种方法及实例讲解
  • Python中list列表的一些进阶使用方法介绍
  • 在Python中操作列表之List.pop()方法的使用
  • python中对list去重的多种方法
  • Python中列表(list)操作方法汇总
  • Python中列表(list)操作方法汇总

相关文章

  • python django事务transaction源码分析详解
  • python实现的用于搜索文件并进行内容替换的类实例
  • python获取beautifulphoto随机某图片代码实例
  • 浅谈python socket函数中,send与sendall的区别与使用方法
  • python访问mysql数据库的实现方法(2则示例)
  • 浅析Python中元祖、列表和字典的区别
  • python抓取最新博客内容并生成Rss
  • 使用FastCGI部署Python的Django应用的教程
  • Python函数学习笔记
  • Python正则表达式介绍

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • Python语法快速入门指南
    • python list语法学习(带例子)
    • Python开发WebService系列教程之REST,web.py,eurasia,Django
    • python实现登陆知乎获得个人收藏并保存为word文件
    • Python处理json字符串转化为字典的简单实现
    • python Django模板的使用方法(图文)
    • 使用Python脚本和ADB命令实现卸载App
    • python常用函数详解
    • python目录与文件名操作例子
    • 在Python中操作列表之List.pop()方法的使用

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有