Most efficient way to remove duplicates from Python list while preserving order and removing the oldest element
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']
How would something like this work?
Thanks.
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] = []
精彩评论