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

Advertisements

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:

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]

Leave a ReplyCancel reply