python delete substrings from list of strings -


i have list l=['abc','abcdef','def','defdef','polopolo'] im trying delete strings superstring in list. in case, result should be:

['abcdef','defdef','polopolo']

i have written code:

l=['abc','abcdef','def','defdef','polopolo'] res=['abc','abcdef','def','defdef','polopolo'] each in l:     l1=[x x in l if x!=each]     other in l1:         if each in other:             res.remove(each) 

but doesnt seem work. have read cannot remove list while iterating on it. hence copy res., while l original list. in advance.

l=['abc','abcdef','def','defdef','polopolo'] print [j i, j in enumerate(l) if all(j not in k k in l[i + 1:])] # ['abcdef', 'defdef', 'polopolo'] 

we can speed little, sorting list before

l = sorted(l, key = len) print [j i, j in enumerate(l) if all(j not in k k in l[i + 1:])] 

as @ashwini chaudhary mentions in comments, if want retain duplicate strings, can this

l = ['abc','defghi' 'abcdef','def','defdef','defdef', 'polopolo'] l = sorted(l, key = len) print [j i,j in enumerate(l) if all(j == k or (j not in k) k in l[i+1:])] # ['defdef', 'defdef', 'polopolo', 'defghiabcdef'] 

Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -