简体   繁体   English

解压n级嵌套列表

[英]Unpacking n-level nested lists

Suppose, I have a list, 假设我有一个清单,

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

I will print 1 + 2 and 3 + 4 if all elements of the list are tuples. 如果列表中的所有元素都是元组,我将打印1 + 2和3 + 4。 But if any one of the elements is also a list, then I add 1 to every element of the inner list and every element of that inner list is appended to the parent list. 但是,如果其中任何一个元素也是一个列表,则我向内部列表的每个元素加1,然后将该内部列表的每个元素附加到父列表。 eg. 例如。

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

becomes 变成

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

Again, if the inner list has a list as an element, we repeat the same thing. 同样,如果内部列表将列表作为元素,则重复同样的事情。 eg. 例如。

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

first becomes 首先成为

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

then finally becomes, 然后终于变成

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

How do I do this procedure to such a list, whose nesting level(as in list in a list in a list....) is not known ? 我如何对这样的列表执行此过程,该列表的嵌套级别(如列表中的列表中的列表...)是未知的?

The code I used to generate this list is as follows: 我用来生成此列表的代码如下:

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))

This solution uses nested generators. 该解决方案使用嵌套生成器。 We loop through the items of our list, checking their types. 我们遍历列表中的项目,检查其类型。 Whenever we see a list , we recursively call flatten on that list, and add 1 to the end of each output. 每当我们看到一个list ,我们都会在该列表上递归调用flatten ,并在每个输出的末尾添加1 If item is a tuple, we just yield it. 如果item是一个元组,我们就产生它。 Then outside flatten , we iterate though the generator to build a list. 然后在flatten之外,我们遍历生成器以构建列表。

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)]
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)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM