Home > OS >  Python List of tuple how to remove duplicates?
Python List of tuple how to remove duplicates?

Time:05-16

I have a small doubt I have a list of tuple

test_lst=[[],
 [],
 [('boy', 20, 23), ('boy', 30, 33)],
 [],
 [('school', 20, 25), ('school', 30, 35)],
 [('jack', 20, 24), ('Mile', 40, 44)]]

I do not want duplicates my final list should look like

final_lst=[[],
 [],
 [('boy', 20, 23)],
 [],
 [('school', 20, 25)],
 [('jack', 20, 24), ('Mile', 40, 44)]]

How can I do that in an optimized way?

CodePudding user response:

You can try using itertools.groupby to check for duplicates of first value in tuple

import itertools
test_lst=[[],
 [],
 [('boy', 20, 23), ('boy', 30, 33)],
 [],
 [('school', 20, 25), ('school', 30, 35)],
 [('jack', 20, 24), ('Mile', 40, 44)]]
final_lst = [[next(b) for a, b in itertools.groupby(x, lambda y: y[0])] for x in test_lst]

CodePudding user response:

final_lst = []
for lst in test_lst:
    names = []
    inner_lst = []
    for x in lst:
            inner_lst.append(x) if x[0] not in names else None
            names.append(x[0])
    final_lst.append(inner_lst)

print(final_lst)

Output:

[[], [], [('boy', 20, 23)], [], [('school', 20, 25)], [('jack', 20, 24), ('Mile', 40, 44)]]
  • Related