我正在寻找类似于nubBy in Haskell的Python函数,它删除重复,但使用不同的等式测试。
该函数将接受等式测试和列表作为参数,并返回没有重复的元素列表。
示例
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中有等效的内置函数吗?如果没有,那么有效地实现它的最佳方法是什么?
发布于 2011-09-04 22:06:23
没有内置方法(因为用例相当深奥),但您可以轻松地编写一个方法:
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]发布于 2011-09-04 22:16:18
这个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))https://stackoverflow.com/questions/7302378
复制相似问题