python - 根据第一个元素从列表列表中仅返回唯一出现
问题描述
抱歉,我认为这是一个常见问题,但似乎无法找到预期结果的确切答案。
我想只返回基于一个元素的列表列表中的唯一项目。
例子;
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]]
推荐阅读
- sql - SQLite - 具有多个连接的复杂 SELECT
- angularjs - 使用新数据问题重绘数据表
- javascript - 显示日期是一个 md-datepicker 字段
- laravel - Laravel 取消创建对象
- javascript - 带有自定义周标题的完整日历自定义议程周视图
- css - 如何在引导程序中减小放置项容器的大小
- ruby-on-rails-3 - NameError(未初始化的常量 Twitter::TextExtractor):
- java - 无法在我的代码中抛出 IllegalArgumentException
- docker - 通过 docker 文件安装 Gradle
- java - 等待构造函数内部的用户输入