Python如何过滤含指定数组元素的子数组并保留最新日期条目
Python 列表过滤实现方案
需求说明
给定两个列表:
ListA = [['abc','15','2021-10-02 08:53:29'], ['def','10','2021-10-01 07:52:19'], ['abc','15','2021-10-02 09:53:29'], ['def','10','2021-10-01 06:52:19'], ['gfc','10','2021-10-01 07:52:19']] ListB = ['abc','def']
需要按以下规则过滤ListA:
- 首元素属于ListB的条目,仅保留该类条目里日期最晚的条目,其余同首元素的旧日期条目删除
- 首元素不属于ListB的条目全部保留
预期输出结果:
[['def','10','2021-10-01 07:52:19'], ['abc','15','2021-10-02 09:53:29'], ['gfc','10','2021-10-01 07:52:19']]
实现思路
- 先遍历一次ListA,统计出ListB中每个元素对应的最晚日期,由于示例中的日期为ISO标准格式,字符串的比较顺序和时间先后顺序完全一致,直接比较字符串即可得到正确结果
- 再次遍历ListA,按规则筛选符合要求的条目组成结果列表
完整实现代码
# 原始数据定义 ListA = [['abc','15','2021-10-02 08:53:29'], ['def','10','2021-10-01 07:52:19'], ['abc','15','2021-10-02 09:53:29'], ['def','10','2021-10-01 06:52:19'], ['gfc','10','2021-10-01 07:52:19']] ListB = ['abc','def'] # 统计每个ListB元素对应的最晚日期 max_date = {} for item in ListA: key = item[0] curr_date = item[2] if key in ListB: if key not in max_date or curr_date > max_date[key]: max_date[key] = curr_date # 按规则过滤 res = [] for item in ListA: key = item[0] if key not in ListB: res.append(item) else: if item[2] == max_date[key]: res.append(item) print(res)
运行输出
[['def', '10', '2021-10-01 07:52:19'], ['abc', '15', '2021-10-02 09:53:29'], ['gfc', '10', '2021-10-01 07:52:19']]
内容的提问来源于stack exchange,提问作者liuxu
相关产品推荐
相关产品推荐

