且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从列表中有效删除与订单无关的重复项

更新时间:2023-12-02 20:33:52

这有点棘手.您想从冻结的计数器中删除字典,但是计数器在Python中不可哈希.为了使渐进复杂度稍有下降,您可以使用已排序的元组代替冻结计数器:

This one is a little tricky. You want to key a dict off of frozen counters, but counters are not hashable in Python. For a small degradation in the asymptotic complexity, you could use sorted tuples as a substitute for frozen counters:

seen = set()
result = []
for x in l1:
    key = tuple(sorted(x))
    if key not in seen:
        result.append(x)
        seen.add(key)

单线的相同想法如下所示:

The same idea in a one-liner would look like this:

[*{tuple(sorted(k)): k for k in reversed(l1)}.values()][::-1]