我已经看到了一些类似的答案,但我找不到针对这种情况的具体内容.
我有一个元组列表:
[(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