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

时间:2015-01-06 10:35:44

标签: python

给出一个列表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

2 个答案:

答案 0 :(得分:4)

你可以使用套装:

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会检查列表ls的{​​{3}}。

或者,如果你喜欢简洁:

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

答案 1 :(得分:0)

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]]
相关问题