基于第一个元素从列表的列表中返回唯一的事件

Returning only unique occurrences from a list of lists based on the first element

抱歉,我认为这是一个常见问题,但似乎无法找到所需结果的确切答案。

我想 return 仅基于一个元素的列表列表中的唯一项。

示例;

List = [[1,2],[2,3],[1,4],[1,5],[6,3]]

期望的结果;

List = [[2,3],[6,3]]

由于 1 作为多个列表项中的第一个元素存在,因此我希望将它们全部忽略。

有没有简单的方法可以做到这一点?

使用 list.count 可能很诱人,但如果天真地使用它会使使用它的解决方案复杂度为 O(n^2)。

O(n) 解决方案将使用 collections.Counter:

from collections import Counter

nested_list = [[1,2],[2,3],[1,4],[1,5],[6,3]]

counter_map = Counter(sublist[0] for sublist  in nested_list)
print(counter_map)
output = [sublist for sublist in nested_list if counter_map[sublist[0]] == 1]
print(output)

产出

Counter({1: 3, 2: 1, 6: 1})
[[2, 3], [6, 3]]