python - 在 Python 中搜索和过滤元组列表
问题描述
我有一个元组列表,我正在尝试根据最小值删除重复项:
a_list = [("1","111","15"),("2","111","10"),("3","111","5"),("4","112","40"),("5","112","10")]
Output :
id id_client value2
1 111 15
2 111 10
3 111 5
4 112 40
5 112 10
Required Output
id id_client value2
3 111 5
5 112 10
我尝试了一切,但无法得到它。
解决方案
试试下面的代码:
# Input list
a_list = [("1","111","15"),("2","111","10"),("3","111","5"),("4","112","40"),("5","112","10")]
# Sort the list by the third value (index-2)
sorted_list = sorted(a_list, key=lambda x: int(x[2]))
# Track visited and repeated elements to only add the first tuple(x) with the smallest x[1]
visited = []
# New list to only append unique tuples
new_list = []
for i in sorted_list:
if i[1] not in visited:
new_list.append(i)
visited.append(i[1])
print(new_list)
输出:
[('1', '111', '15'), ('4', '112', '40')]
推荐阅读
- javascript - 无法读取 null 的读取属性“样式”
- javascript - 如何把视频全屏
- c - 为什么 GCC 不支持多线程编译?
- python - 如何确定与我的数据相关的统计测试
- html - Laravel 8 如果标题相同,则合并 HTML 表格列
- airflow - 通过 Airflow 在网络服务器和调度程序中创建文件夹
- python - 为什么 python statistics.mean() 函数在传递 numpy.ndarray 或列表时表现不同?
- python - 用 numpy 快速乘以逐行子矩阵
- vue.js - SVG 和动态调整大小 - vuejs
- reactjs - React 项目中的打字稿不再识别“as”关键字