【问题标题】:How to remove a sublist in nested list that are in another sublist?如何删除嵌套列表中另一个子列表中的子列表?
【发布时间】:2019-08-02 10:48:57
【问题描述】:

我有一个清单:

a = [[2,3,4],[2,3,4],[2,3],[1,5,4],[1,5]]

我想得到:

b = [[2,3,4],[1,5,4]]

[2,3,4] 是重复的,[2,3], [1,5] 完全被 [2,3,4],[1,5,4] 包含,所以我想删除它

我使用set(frozenset(x) for x in a) 删除重复项,但我被如何删除 [2,3],[1,5] 中的另一个子列表所包含的方法卡住了

【问题讨论】:

    标签: python python-3.x list duplicates set


    【解决方案1】:

    您可以将a 中的子列表转换为集合并按长度以相反的顺序对其进行排序,这样您就可以遍历它们并将每个集合添加到输出中,前提是它不是任何集合的子集输出中的现有集合:

    output = []
    for candidate in sorted(map(set, a), key=len, reverse=True):
        if not any(candidate <= incumbent for incumbent in output):
            output.append(candidate)
    

    list(map(list, output)) 返回:

    [[2, 3, 4], [1, 4, 5]]
    

    然而,集合是无序的,所以如果子列表中的原始项目顺序很重要,您可以利用字典键从 Python 3.7 开始排序的事实,并将子列表映射到字典键:

    output = []
    for candidate in sorted(map(dict.fromkeys, a), key=len, reverse=True):
        if not any(candidate.keys() <= incumbent.keys() for incumbent in output):
            output.append(candidate)
    

    这样list(map(list, output)) 返回:

    [[2, 3, 4], [1, 5, 4]]
    

    如果您使用的是 Python 3.6 或更早版本,其中 dict 键的顺序无法保证,您可以使用 collections.OrderedDict 代替 dict。

    【讨论】:

      猜你喜欢
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-29
      • 1970-01-01
      相关资源
      最近更新 更多