首页 > 解决方案 > 根据第一个元素从列表列表中仅返回唯一出现

问题描述

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

我想只返回基于一个元素的列表列表中的唯一项目。

例子;

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

期望的结果;

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

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

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

标签: pythonpython-3.xnested-lists

解决方案


使用它可能很诱人,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]]

推荐阅读