繁体   English   中英

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

[英]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检查列表ls适当子集

或者,如果您喜欢简洁:

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]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM