Python cookbook(数据结构与算法)从序列中移除重复项且保持元素间顺序不变的方法
作者:垄上行 时间:2023-03-01 14:24:38
本文实例讲述了Python从序列中移除重复项且保持元素间顺序不变的方法。分享给大家供大家参考,具体如下:
问题:从序列中移除重复的元素,但仍然保持剩下的元素顺序不变
解决方案:
1、如果序列中的值时可哈希(hashable)的,可以通过使用集合和生成器解决。
# example.py
#
# Remove duplicate entries from a sequence while keeping order
def dedupe(items):
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
if __name__ == '__main__':
a = [1, 5, 2, 1, 9, 1, 5, 10]
print(a)
print(list(dedupe(a)))
运行结果:
[1, 5, 2, 1, 9, 1, 5, 10]
[1, 5, 2, 9, 10]
2、如果序列时不可哈希的,想要去除重复项,需要对上述代码稍作修改:
# example2.py
#
# Remove duplicate entries from a sequence while keeping order
def dedupe(items, key=None):
seen = set()
for item in items:
val = item if key is None else key(item)
if val not in seen:
yield item
seen.add(val)
if __name__ == '__main__':
a = [
{'x': 2, 'y': 3},
{'x': 1, 'y': 4},
{'x': 2, 'y': 3},
{'x': 2, 'y': 3},
{'x': 10, 'y': 15}
]
print(a)
print(list(dedupe(a, key=lambda a: (a['x'],a['y']))))
运行结果:
[{'x': 2, 'y': 3}, {'x': 1, 'y': 4}, {'x': 2, 'y': 3}, {'x': 2, 'y': 3}, {'x': 10, 'y': 15}]
[{'x': 2, 'y': 3}, {'x': 1, 'y': 4}, {'x': 10, 'y': 15}]
key
参数的作用是指定一个函数用来将序列中的元素转化为可哈希的类型,如此可以检测重复项。
(代码摘自《Python Cookbook》)
希望本文所述对大家Python程序设计有所帮助。
来源:http://www.cnblogs.com/apple2016/p/5746729.html
标签:Python,数据结构,算法,序列
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
高性能WEB开发 JS、CSS的合并、压缩、缓存管理
2023-01-02 11:03:26
![](https://img.aspxhome.com/file/2023/5/78395_0s.jpg)
python字符串切片及常用方法示例详解
2021-01-02 15:40:20
sqlserver中在指定数据库的所有表的所有列中搜索给定的值
2011-09-30 11:27:38
python beautiful soup库入门安装教程
2023-03-04 06:24:27
![](https://img.aspxhome.com/file/2023/2/92092_0s.png)
python+opencv实现目标跟踪过程
2023-03-29 01:29:15
![](https://img.aspxhome.com/file/2023/4/67394_0s.gif)
Python实现统计单词出现的个数
2022-11-01 12:19:30
150行python代码实现贪吃蛇游戏
2021-07-15 06:43:20
![](https://img.aspxhome.com/file/2023/4/103164_0s.jpg)
Python基于递归算法实现的汉诺塔与Fibonacci数列示例
2021-07-01 15:57:12
![](https://img.aspxhome.com/file/2023/6/89166_0s.jpg)
弹出网页窗口全详细攻略
2008-04-18 12:10:00
一篇文章带你了解python标准库--sys模块
2022-04-25 10:21:37
网站制作流程及界面交互设计
2007-10-26 12:00:00
![](https://img.aspxhome.com/file/UploadPic/200710/26/2007102612842449s.jpg)
10款最好的Web开发的 Python 框架
2023-12-21 11:26:04
![](https://img.aspxhome.com/file/2023/5/134605_0s.jpg)
MySQL 5.7 create VIEW or FUNCTION or PROCEDURE
2024-01-20 18:58:16
Python实现自动登录百度空间的方法
2023-11-11 09:11:23
python实现好看的时钟效果
2021-02-11 23:44:25
![](https://img.aspxhome.com/file/2023/6/77796_0s.gif)
如何恢复MySQL主从数据一致性
2024-01-26 23:34:33
![](https://img.aspxhome.com/file/2023/7/95617_0s.png)
Python Pygame实战之实现经营类游戏梦想小镇代码版
2021-08-06 19:13:23
![](https://img.aspxhome.com/file/2023/7/113027_0s.png)
python根据list重命名文件夹里的所有文件实例
2022-02-12 15:54:30
python3使用requests模块爬取页面内容的实战演练
2022-01-08 18:26:57
![](https://img.aspxhome.com/file/2023/5/90625_0s.png)
“mailto”的六则应用技巧
2008-08-29 13:16:00