[英]Python: removing duplicates from a list while preserving order using a dictionary
[英]Most efficient way to remove duplicates from Python list while preserving order and removing the oldest element
我在网站上看到了一堆解决方案来删除重复项,同时保留最旧的元素。 我对相反感兴趣:在保留最新元素的同时删除重复项,例如:
list = ['1234','2345','3456','1234']
list.append('1234')
>>> ['1234','2345','3456','1234','1234']
list = unique(list)
>>> ['2345','3456','1234']
这样的事情怎么样?
谢谢。
要求项目(或键)可以清洗,在列表中就地工作:
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] = []
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.