You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

三层嵌套列表处理:删除被包含子列表,保留元素最多的子列表

处理三层嵌套列表的被包含子列表删除问题

需求明确:给定三层嵌套列表,删除所有被其他子列表包含的项,仅保留未被任何其他子列表包含的元素(被包含的子列表长度必然小于包含它的列表)。

示例输入

input_list = [
    [[1981, 1983, 1985, 1986, 1987, 1988, 1989]],
    [[1982, 1984, 1985]],
    [[1983, 1985, 1986, 1987, 1988, 1989]],
    [[1984, 1985]],
    [[1985, 1986, 1987, 1988, 1989]]
]

期望输出

output_list = [
    [[1981, 1983, 1985, 1986, 1987, 1988, 1989]],
    [[1982, 1984, 1985]],
    [[1984, 1985]],
]

解决思路与代码实现

三层嵌套的核心是先提取最内层列表简化逻辑,处理完成后再重构回三层结构:

  1. 提取内层列表:把每个[[year_list]]结构转换成year_list,得到普通二维列表
  2. 判断子集关系:对每个内层列表,检查是否存在另一个列表,使得当前列表是它的子集且长度更短(说明当前列表被包含)
  3. 筛选并重构结构:保留未被任何其他列表包含的项,再包装回三层嵌套格式
def filter_contained_lists(nested_list):
    # 提取最内层列表,简化后续处理
    inner_lists = [item[0] for item in nested_list]
    filtered = []
    
    for idx, current in enumerate(inner_lists):
        current_set = set(current)
        is_contained = False
        # 遍历其他所有内层列表,判断是否被包含
        for other_idx, other in enumerate(inner_lists):
            if idx == other_idx:
                continue
            # 子集判断+长度校验,确认当前列表被其他列表包含
            if current_set.issubset(set(other)) and len(current) < len(other):
                is_contained = True
                break
        # 未被包含则保留原三层结构的项
        if not is_contained:
            filtered.append(nested_list[idx])
    
    return filtered

# 测试示例
input_list = [
    [[1981, 1983, 1985, 1986, 1987, 1988, 1989]],
    [[1982, 1984, 1985]],
    [[1983, 1985, 1986, 1987, 1988, 1989]],
    [[1984, 1985]],
    [[1985, 1986, 1987, 1988, 1989]]
]

result = filter_contained_lists(input_list)
print(result)

代码说明

  • 用set的issubset方法高效判断子集关系,比逐个遍历元素更简洁
  • 遍历过程中跳过自身,避免误判
  • 直接从原嵌套列表中取对应项,保证输出结构与输入完全一致

内容的提问来源于stack exchange,提问作者ASking

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 04:54:12