![](/img/trans.png)
[英]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.