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

n-n级嵌套列表

  •  1
  • vighnesh153  · 技术社区  · 7 年前

    假设,我有一个清单,

    [(1,2), (3, 4)].
    

    但是如果其中任何一个元素也是一个列表,那么我将为内部列表的每个元素添加1,并且该内部列表的每个元素都会附加到父列表。 如。

    list = [(1,2), [(3, 4), (5, 6)]], 
    

    变成

    [(1, 2), (3, 4, 1), (5, 6, 1)].
    

    如。

    [(1,2), [(3, 4), (5, 6), [(7, 8)]]] 
    

    第一个变成

    [(1,2), [(3, 4), (5, 6), (7, 8, 1)]] 
    

    最后变成了,

    [(1,2), (3, 4, 1), (5, 6, 1), (7, 8, 1, 1)].
    

    如何对这样一个嵌套级别(如列表中的列表….)未知的列表执行此过程?

    我用来生成这个列表的代码如下:

    def possible_sums(a):
        if a == 2:
            return [(1, 1)]
        list_l = list(((a - 1, 1), ))
        list_l.append(possible_sums(a-1))
        return list_l
    
    
    print(possible_sums(8))
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   Patrick Haugh    7 年前

    此解决方案使用嵌套生成器。我们循环检查列表中的项目,检查它们的类型。每当我们看到 list flatten 1 到每个输出的末尾。如果 item 是一个元组,我们只需让它。然后在外面 压平 ,我们遍历生成器来构建一个列表。

    def flattener(lst):
        for item in lst:
            if isinstance(item, list):
                gen = flattener(item)
                for item in gen:
                    yield item + (1,)
            elif isinstance(item, tuple):
                yield item
    
    
    print(list(flattener([(1,2), [(3, 4), (5, 6), [(7, 8)]], [(5, 6, 7), [(1, 2)]]])))
    # [(1, 2), (3, 4, 1), (5, 6, 1), (7, 8, 1, 1), (5, 6, 7, 1), (1, 2, 1, 1)]
    
        2
  •  1
  •   Tanmay jain    7 年前
    nested_lst = [(1,2), [(3, 4), (5, 6), [(7, 8)]] ,(2,3),[(6,7)]] 
    output = []
    
    def de_nestify(lst,lvl):
    
        if len(lst) != 0:
            for item in lst:
                if isinstance(item, list):
                    lvl += 1
                    de_nestify(item,lvl)
                    lvl = 0 #reset nesting lvl
    
                else:
                    item += (1,)*lvl
                    output.append(item)
    
    
    de_nestify(nested_lst,0)
    
    print(output) 
    #[(1, 2), (3, 4, 1), (5, 6, 1), (7, 8, 1, 1), (2, 3), (6, 7, 1)]