python - 当顺序很重要时如何从元组列表中删除重复项

标签 python list duplicates tuples

我看到了一些类似的答案,但我找不到针对这种情况的具体答案。

我有一个元组列表:

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

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

所以输出应该是这样的:

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

最佳答案

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

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

关于python - 当顺序很重要时如何从元组列表中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47246912/

相关文章:

Python socketIO-client 连接然后断开

java - 给定列表列表的唯一元素列表

c++ - 使用迭代器从列表中打印结构值

mysql查询以获取每个给定键的记录

c# - Distinct() 方法是否保持序列的原始顺序不变?

python - 过滤字典中常见的子字典键

python - 将不同的聚合应用于 pandas GroupBy 组

python - 040和40的区别

java - 在 java 中创建整数列表 - 不能使用 new List<Integer>();

javascript - 如何将字符串添加到列表中而不重复