在Python中使用不同的相等测试去除重复项

2 投票
2 回答
504 浏览
提问于 2025-04-17 01:26

我在找一个Python函数,类似于nubBy在Haskell中的功能,它可以去掉重复的元素,但使用不同的比较方式。

这个函数会接收一个比较方法和一个列表作为参数,然后返回一个没有重复元素的列表。

举个例子:

In [1]: remove(lambda x, y: x+y == 12, [2, 3, 6, 9, 10])
Out[1]: [2,3,6]

比如在这里,(2和10)以及(9和3)是重复的。我不在乎输出是[10, 9, 6]还是[2, 3, 6]

在Python中有没有类似的内置函数?如果没有,怎么才能高效地实现这个功能呢?

2 个回答

1

这个 remove 函数让你可以指定任何一对一比较的方式。它会保留每组重复项中的最后一个。

values = [2,3,5,7,8]

def addstoten(item, other):
    return item + other == 10

def remove(eq, values):
    values = tuple(values)
    for index, item in enumerate(values):
        if not any(eq(item, other) for other in values[index + 1:]):
            yield item

print list(remove(addstoten, values))
2

没有现成的方法(因为这个用例比较冷门),不过你可以很简单地自己写一个:

def removeDups(duptest, iterable):
  res = []
  for e in iterable:
    if not any(duptest(e, r) for r in res):
       res.append(e)
  return res

现在,在控制台里:

>>> removeDups(lambda x,y: x+y == 10, [2,3,5,7,8])
[2, 3, 5]
>>> removeDups(lambda x,y: x+y == 10, [2,3,6,7,8])
[2, 3, 6]
>>> removeDups(lambda x, y: x+y == 12, [2, 3, 6, 9, 10])
[2, 3, 6]

撰写回答