Given a list t
:
[[0, 4], [0, 4, 5, 7], [1, 2, 3, 6], [1, 3], [2, 6], [5, 7]]
I want to remove sublists in t
, eg [0,4]
, both numbers in which already exist in [0,4,5,7]
, I want to keep the larger groups and remove smaller groups. And so in the end [[0, 4, 5, 7], [1,2,3,6]]
will be my final results.
I have tried the following code but don't know what is wrong:
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
You could use sets for this:
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
Here, set(l) < s
checks that the list l
is a proper subset of s
.
Or, if you like conciseness:
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]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.