Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove lists of list that has a specific duplicate index without keeping the first one found and keeping order

If I had a simple list of values I could totally remove the duplicates like this:

lines = ['a','b','a']

final_lines = [l for l in lines if lines.count(l) == 1]

Output:

['b']

But when I have list of lists and I want to specifically analise the index [0] for duplicate values and remove the lists if exist duplicate:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

lines = [['a','b','c','d'],['e','f','g','h'],['a','j','k','l']]

final_lines = [l for l in lines if lines.count(l[0]) == 1]
final_lines = [l for l in lines if l[0].count(l[0]) == 1]
final_lines = [l for l in lines if l[0].count(lines[0][0]) == 1]

This option not returns this desired output:

[['e','f','g','h']]

Info add:

After creating the question I ended up bumping into a new attempt:

final_lines = [l for l in lines if l[0].count(lines[0][0]) == 0]

but only works if only one index repeat, if there one more like this:

lines = [['a','b','c','d'],['e','f','g','h'],['e','f','g','h'],['a','j','k','l']]

Instead of it returning:

[]

Return:

[['e', 'f', 'g', 'h'], ['e', 'f', 'g', 'h']]

>Solution :

One approach: use a list of what you want to compare for each item:

firsts = [x[0] for x in lines]

final_lines = [l for l in lines if firsts.count(l[0]) == 1]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading