Python cookbook(数据结构与算法)从序列中移除重复项且保持元素间顺序不变的方法

yipeiwu_com6年前Python基础

本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python查找目录下指定扩展名的文件实例

本文实例讲述了python查找目录下指定扩展名的文件。分享给大家供大家参考。具体如下: 这里使用python查找当前目录下的扩展名为.txt的文件 import os items =...

python执行shell获取硬件参数写入mysql的方法

本文实例讲述了python执行shell获取硬件参数写入mysql的方法。分享给大家供大家参考。具体分析如下: 最近要获取服务器各种参数,包括cpu、内存、磁盘、型号等信息。试用了Hyp...

django迁移数据库错误问题解决

django.db.migrations.graph.NodeNotFoundError: Migration order.0002_auto_20181209_0031 depen...

python中in在list和dict中查找效率的对比分析

首先给一个简单的例子,测测list和dict查找的时间: import time query_lst = [-60000,-6000,-600,-60,-6,0,6,60,600,6...

通过mod_python配置运行在Apache上的Django框架

为了配置基于 mod_python 的 Django,首先要安装有可用的 mod_python 模块的 Apache。 这通常意味着应该有一个 LoadModule 指令在 Apache...