在保留顺序和删除最旧元素的同时从Python列表中删除重复项的最有效方法 [英] Most efficient way to remove duplicates from Python list while preserving order and removing the oldest element

查看:95
本文介绍了在保留顺序和删除最旧元素的同时从Python列表中删除重复项的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网站上看到了很多解决方案,可以在保留最旧元素的同时删除重复项.我对相反的东西很感兴趣:在保留最新元素的同时删除重复项,例如:

I've seen a bunch of solutions on the site to remove duplicates while preserving the oldest element. I'm interested in the opposite: removing duplicates while preserving the newest element, for example:

list = ['1234','2345','3456','1234']
list.append('1234')
>>> ['1234','2345','3456','1234','1234']
list = unique(list)
>>> ['2345','3456','1234']

这种方式如何工作?

谢谢.

推荐答案

要求项(或键)是可散列的,就可以在类似列表的地方工作:

Requires the items (or keys) to be hashable, works in-place on list-likes:

def inplace_unique_latest(L, key=None):
  if key is None:
    def key(x):
      return x
  seen = set()
  n = iter(xrange(len(L) - 1, -2, -1))
  for x in xrange(len(L) - 1, -1, -1):
    item = L[x]
    k = key(item)
    if k not in seen:
      seen.add(k)
      L[next(n)] = item
  L[:next(n) + 1] = []

这篇关于在保留顺序和删除最旧元素的同时从Python列表中删除重复项的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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