Python cookbook(数据结构与算法)从序列中移除重复项且保持元素间顺序不变的方法 本文实例讲述了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程序设计有所帮助。