当订单重要时,如何从元组列表中删除重复项 [英] How to remove duplicate from list of tuple when order is important

查看:80
本文介绍了当订单重要时,如何从元组列表中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了一些类似的答案,但是我找不到针对这种情况的特定内容.

I have seen some similar answers, but I can't find something specific for this case.

我有一个元组列表:

[(5, 0), (3, 1), (3, 2), (5, 3), (6, 4)]

我想要的是仅在列表中先前出现过元组的第一个元素并且剩下的元组应该具有最小的第二个元素时才从此列表中删除元组.

What I want is to remove tuples from this list only when first element of tuple has occurred previously in the list and the tuple which remains should have the smallest second element.

所以输出应如下所示:

[(5, 0), (3, 1), (6, 4)]

推荐答案

这是一种线性时间方法,需要在原始列表上进行两次迭代.

Here's a linear time approach that requires two iterations over your original list.

t = [(5, 0), (3, 1), (3, 2), (5, 3), (6, 4)] # test case 1
#t = [(5, 3), (3, 1), (3, 2), (5, 0), (6, 4)] # test case 2
smallest = {}
inf = float('inf')

for first, second in t:
    if smallest.get(first, inf) > second:
        smallest[first] = second

result = []
seen = set()

for first, second in t:
    if first not in seen and second == smallest[first]:
        seen.add(first)
        result.append((first, second))

print(result) # [(5, 0), (3, 1), (6, 4)] for test case 1
              # [(3, 1), (5, 0), (6, 4)] for test case 2

这篇关于当订单重要时,如何从元组列表中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆