脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python cookbook(数据结构与算法)从序列中移除重复项且保持元素间顺序不变的方法

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

2021-01-21 00:26垄上行 Python

这篇文章主要介绍了Python cookbook(数据结构与算法)从序列中移除重复项且保持元素间顺序不变的方法,涉及Python针对列表与字典的元素遍历、判断、去重、排序等相关操作技巧,需要的朋友可以参考下

本文实例讲述了Python从序列中移除重复项且保持元素间顺序不变的方法。分享给大家供大家参考,具体如下:

问题:从序列中移除重复的元素,但仍然保持剩下的元素顺序不变

解决方案:

1、如果序列中的值时可哈希(hashable)的,可以通过使用集合和生成器解决。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
# 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
2
[1, 5, 2, 1, 9, 1, 5, 10]
[1, 5, 2, 9, 10]

2、如果序列时不可哈希的,想要去除重复项,需要对上述代码稍作修改:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 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']))))

运行结果:

?
1
2
[{'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

延伸 · 阅读

精彩推荐