Python元组列表如何去重?

Python List of tuple how to remove duplicates?

我有点怀疑我有一个元组列表

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

我不想重复我的最终列表应该是这样的

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

我怎样才能以优化的方式做到这一点?

您可以尝试使用 itertools.groupby 检查元组中第一个值的重复项

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]
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)

输出:

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