清单元素包括在其他元素中

时间:2018-09-19 05:59:30

标签: python list

我的列表为:

Lt = [((5,14),(8,14),(10,4)),((5,14),(8,14),(9,14)),((5,14),(8,14)),((5,14),(6,4),(8,14)),
       ((8,14),(9,14)),((8,14),(10,4))]

我想得到:

Lt = [((5,14),(8,14),(10,4)),((5,14),(8,14),(9,14)),((5,14),(6,4),(8,14))]

这意味着,如果Lt [i]包含Lt [j],则Lt [j]将被删除。

这是我的丑陋代码:

def filter_clique(old_center):
# [(('X', 2), ('f', 6)), (('X', 2), ('O', 3)), (('X', 2), ('O', 3),('f', 6))]
# return: [(('X', 2), ('O', 3),('f', 6))]
# first: sorted list
old_center = sorted(old_center, key=lambda m: len(m), reverse=True)
rm_index = []
lth = len(old_center)
for i in range(lth-1):
    for j in range(i+1, lth):
        if set(old_center[j]).issubset(set(old_center[i])):
            rm_index.append(j)
if len(rm_index):
    old_center = np.delete(old_center, rm_index).tolist()
    return old_center
else:
    return old_center

如果我的清单比较大,此过程将变得非常昂贵。

哪种方法最快? 谢谢!

2 个答案:

答案 0 :(得分:0)

这是新尝试:

sets = list(map(set, Lt))
new_list = [l for l,s in zip(Lt, sets) if not any(s < other for other in sets)]
print(new_list)

# [(5, 14, 8, 14, 10, 4), (5, 14, 6, 4, 8, 14), (5, 14, 8, 14, 9, 14)]

答案 1 :(得分:0)

这是一种方法。

演示:

Lt = [(5,14,8,14,10,4),(5,14,8,14,9,14),(5,14,8,14),(5,14,6,4,8,14),(8,14,9,14),(8,14,10,4)]
Lt = sorted(set(Lt), key=lambda m: len(m), reverse=True)
res = []
while Lt:
    val = Lt.pop()
    if not any(set(val).issubset(set(i)) for i in Lt):
        res.append(val)
print(res)

输出:

[(5, 14, 8, 14, 10, 4), (5, 14, 8, 14, 9, 14), (5, 14, 6, 4, 8, 14)]