算法 - 如何有效地删除列表中的重复元素? [英] Algorithm - How to delete duplicate elements in a list efficiently?

查看:31
本文介绍了算法 - 如何有效地删除列表中的重复元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个列表L.它包含任意类型的元素.如何有效地删除此类列表中的所有重复元素?必须保留订单

只需要一个算法,所以不允许导入任何外部库.

相关问题

解决方案

假设订单很重要:

  • 创建一个空集 S 和一个空列表 M.
  • 一次扫描列表 L 一个元素.
  • 如果元素在集合 S 中,则跳过它.
  • 否则,将其添加到 M 和 S.
  • 对 L 中的所有元素重复.
  • 返回 M.

在 Python 中:

<预><代码>>>>L = [2, 1, 4, 3, 5, 1, 2, 1, 1, 6, 5]>>>S = 设置()>>>M = []>>>对于 L 中的 e:...如果 e 在 S 中:... 继续... S.add(e)... M.append(e)...>>>米[2, 1, 4, 3, 5, 6]

如果顺序无关紧要:

M = list(set(L))

There is a list L. It contains elements of arbitrary type each. How to delete all duplicate elements in such list efficiently? ORDER must be preserved

Just an algorithm is required, so no import any external library is allowed.

Related questions

解决方案

Assuming order matters:

  • Create an empty set S and an empty list M.
  • Scan the list L one element at a time.
  • If the element is in the set S, skip it.
  • Otherwise, add it to M and to S.
  • Repeat for all elements in L.
  • Return M.

In Python:

>>> L = [2, 1, 4, 3, 5, 1, 2, 1, 1, 6, 5]
>>> S = set()
>>> M = []
>>> for e in L:
...     if e in S:
...         continue
...     S.add(e)
...     M.append(e)
... 
>>> M
[2, 1, 4, 3, 5, 6]

If order does not matter:

M = list(set(L))

这篇关于算法 - 如何有效地删除列表中的重复元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆