代码之家  ›  专栏  ›  技术社区  ›  Sean

如何将较小的子元素合并到列表中较大的父元素中?

  •  0
  • Sean  · 技术社区  · 5 年前

    我有一个列表列表,但有些列表是其他列表的“子列表”。我想做的是从更大的列表中删除子列表,这样我们只有最大的唯一子列表。

    例如:

    >>> some_list = [[1], [1, 2], [1, 2, 3], [1, 4]]
    >>> ideal_list = [[1, 2, 3], [1, 4]]
    

    我现在写的代码是:

    new_list = []
    
    for i in range(some_list)):
        for j in range(i + 1, len(some_list)):
            count = 0
            for k in some_list[i]:
                if k in some_list[j]:
                    count += 1
            if count == len(some_list[i]):
                new_list.append(some_list[j])
    

    我想到的基本算法是,我们要检查一个列表的元素是否在下面的子列表中,如果是这样的话,我们就使用另一个更大的子列表。它没有给出期望的输出(它实际上给出了 [[1, 2], [1, 2, 3], [1, 4], [1, 2, 3]] )我想知道我能做些什么来实现我想要的。

    我不想使用集合,因为重复的元素很重要。

    3 回复  |  直到 5 年前
        1
  •  1
  •   Marat    5 年前

    set ,但使用 Counter 相反在子列表检查部分,它应该比暴力更有效

    from collections import Counter
    
    new_list = []
    counters = []
    for arr in sorted(some_list, key=len, reverse=True):
        arr_counter = Counter(arr)
        if any((c & arr_counter) == arr_counter for c in counters):
            continue  # it is a sublist of something else
        new_list.append(arr)
        counters.append(arr_counter)
        
    
        2
  •  0
  •   Sean    5 年前

    从@mkrieger1的评论中得到一些启发,一个可能的解决方案是:

    def merge_sublists(some_list):
        new_list = []
        for i in range(len(some_list)):
            true_or_false = []
            for j in range(len(some_list)):
                if some_list[j] == some_list[i]:
                    continue
                true_or_false.append(all([x in some_list[j] for x in some_list[i]]))
            if not any(true_or_false):
                new_list.append(some_list[i])
    
        return new_list
    

    如评论中所述,蛮力解决方案是循环遍历每个元素,并检查它是否是任何其他子列表的子列表。如果是 ,然后将其附加到新列表中。

    测试用例:

    >>> merge_sublists([[1], [1, 2], [1, 2, 3], [1, 4]])
    [[1, 2, 3], [1, 4]]
    >>> merge_sublists([[1, 2, 3], [4, 5], [3, 4]])
    [[1, 2, 3], [4, 5], [3, 4]]
    
        3
  •  0
  •   sharathnatraj    5 年前

    输入:

    l = [[1], [1, 2], [1, 2, 3], [1, 4]]
    

    这里有一条路:

    l1 = l.copy()
    for i in l:
        for j in l:
            if set(i).issubset(set(j)) and i!=j:
                l1.remove(i)
                break
    

    这张照片是:

    print(l1) 
    [[1, 2, 3], [1, 4]]
    

    编辑:(同时处理副本)

    l1 = [list(tupl) for tupl in {tuple(item) for item in l }]
    l2 = l1.copy()
    for i in l1:
        for j in l1:
            if set(i).issubset(set(j)) and i!=j:
                l2.remove(i)
                break
    
    推荐文章