Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserving the order in difference between two lists

I have two lists l and l_match. l_match is an empty list.

l = ['gtttaattgagttgtcatatgttaataacg',
     'tttaattgagttgtcatatgttaataacgg',
     'ttaattgagttgtcatatgttaataacggt',
     'taattgagttgtcatatgttaataacggta',
     'aattgagttgtcatatgttaataacggtat']

l_match = []

print list(set(l) - set(l_match))

gives the output

['aattgagttgtcatatgttaataacggtat',
 'tttaattgagttgtcatatgttaataacgg',
 'ttaattgagttgtcatatgttaataacggt',
 'taattgagttgtcatatgttaataacggta',
 'gtttaattgagttgtcatatgttaataacg']

I want the output the same order as the input. i.e. in the above case the output should be

['gtttaattgagttgtcatatgttaataacg',
 'tttaattgagttgtcatatgttaataacgg',
 'ttaattgagttgtcatatgttaataacggt',
 'taattgagttgtcatatgttaataacggta',
 'aattgagttgtcatatgttaataacggtat']

Can you suggest edits?

like image 818
Ssank Avatar asked Sep 13 '25 06:09

Ssank


1 Answers

Just make l_match a set:

l_match = []

st =  set(l_match)

print([ele for ele in l if ele not in st])

If l can have dupes use an OrderedDict to get unique values from l:

from collections import OrderedDict
print([ele for ele in OrderedDict.fromkeys(l) if ele not in st])

Obviously l_match would contain values in the real world or a simple l[:] = OrderedDict.fromkeys(l) would suffice to remove dupes from l and keep the order

like image 72
Padraic Cunningham Avatar answered Sep 14 '25 19:09

Padraic Cunningham