python删除旧元素_在保留顺序并删除最旧元素的同时从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']

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] = []

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值