从列表中删除一个子列表,其中数字已经存在于另一个子列表中

Remove a sublist from a list in which the numbers alreadys exist in another sublist

给定一个列表 t:

[[0, 4], [0, 4, 5, 7], [1, 2, 3, 6], [1, 3], [2, 6], [5, 7]]

我想删除 t 中的子列表,例如[0,4][0,4,5,7] 中已经存在的两个数字,我想保留较大的组并删除较小的组。所以最后[[0, 4, 5, 7], [1,2,3,6]]就是我的最终结果。

我试过下面的代码,但不知道哪里出了问题:

V=0
while V<60:
    for o in t:
        for p in t:
            if o!= p:
                for s in range(len(o)):
                    w=[]
                    if o[s] in p:
                        w.append(o[s])
                        #print w
                    if w==o:
                        t.remove(w)
    V=V+1
print t

您可以为此使用集合:

lists = [[0, 4], [0, 4, 5, 7], [1, 2, 3, 6], [1, 3], [2, 6], [5, 7]]

sets = map(set, lists)
ret = []
for l in lists:
  if not any(set(l) < s for s in sets):
    ret.append(l)
print ret

在这里,set(l) < s 检查列表 lsproper subset

或者,如果您喜欢简洁:

sets = map(set, lists)
ret = [l for l in lists if not any(set(l) < s for s in sets)]
print ret
l = [[0, 4], [0, 4, 5, 7], [1, 2, 3, 6], [1, 3], [2, 6], [5, 7]]
final = l[:]

for m in l:
    for n in l:
        if set(m).issubset(set(n)) and m != n:
            final.remove(m)
            break   
print final

output: 
[[0, 4, 5, 7], [1, 2, 3, 6]]