我有一个包含n个长度为4的数组列表,例如(n=2):
l = [[1, 2, 3, 4], [5, 6, 7, 8]]
我正在尝试查找列表中的所有“非支配”元素-也就是它们不被列表中的任何其他元素所支配。如果一个数组中的每个项都小于或等于另一个数组中对应的项,那么该数组就支配另一个数组。
dominates([1, 2, 3, 4], [5, 6, 7, 8]) == True
作为 1 <= 5 and 2 <= 6 and 3 <= 7 and 4 <= 8
,但
dominates([1, 2, 3, 9], [5, 6, 7, 8]) == False
作为 9 > 8
。这个函数相对容易编写,例如:
def dominates(a, b):
return all(i <= j for i, j in zip(a, b))
更简洁地说,给定
l = [a1, a2, a3, .., an]
,其中 a
是长度为4的数组,我想找到所有没有被其他 a in l
支配的 a
。我的解决方案如下:
def get_non_dominated(l):
to_remove = set()
for ind, item_1 in enumerate(l):
if item_2 in to_remove:
continue
for item_2 in l[ind + 1:]:
if dominates(item_2, item_1):
to_remove.add(item_1)
break
elif dominates(item_1, item_2):
to_remove.add(item_2)
return [i for i in l if i not in to_remove]
所以
get_non_dominated([[1, 2, 3, 4], [5, 6, 7, 8]])
应该返回[[1, 2, 3, 4]]
。同样地,get_non_dominated([[1, 2, 3, 9], [5, 6, 7, 8]])
应该按照上述逻辑不变地返回该列表(没有任何元素占优)。但这个检查会发生很多次,而且
l
可能非常大。我在想是否有办法加速这个过程?我的第一个想法是尝试使用numpy对这段代码进行向量化,但我对此的经验相对较少,有些困难。您可以假设l
包含所有唯一的数组。非常感谢您提供任何想法!