简体   繁体   English

如何将一个多重嵌套列表附加到一个空列表中?

[英]How to append a multiply nested list into and empty one?

I've seen this code in a book: 我在一本书中看到了以下代码:

def print_loop(items):
    for i in items: 
        if isinstance(i, list):
            print_loop(i)
        else:
            print(i)

What this does is it prints out a multiply nested list. 它的作用是打印出一个多重嵌套列表。 Works perfectly fine with any multiply layered list. 适用于任何多层列表。

I thought how about if we modify the function so that it simply appends the multiply nested list to an empty list. 我考虑过如何修改函数,以便将简单地将嵌套嵌套列表追加到空列表。 Here is how I changed it: 这是我的更改方式:

def append_loop(items):
    func_items = []

    for i in items: 
        if isinstance(i, list):
            append_loop(i)
        else:
            func_items.append(i)
    return func_items

If I have a list like: items = [1,2,3 [4,5, [6,7]]] and try with with my function, all it return is [1,2,3]. 如果我有一个列表,例如: items = [1,2,3 [4,5, [6,7]]]并尝试使用我的函数,则返回的全部是[1,2,3]。

When you call append_loop(i) , this is returning a flattened list. 当您调用append_loop(i) ,这将返回一个扁平化的列表。 You have to do something with that, for instance extending func_items with it: 您必须对此进行处理,例如,使用它扩展func_items

>>> def append_loop(items):
...   func_items = []
...   for i in items:
...       if isinstance(i, list):
...           func_items.extend(append_loop(i))
...       else:
...           func_items.append(i)
...   return func_items
...
>>> append_loop([1,2,[3,[4,5]]])
[1, 2, 3, 4, 5]

Otherwise, you could use a global list: 否则,您可以使用global列表:

>>> global_func_items = []
>>> def append_loop2(items):
...   for i in items:
...       if isinstance(i, list):
...           append_loop2(i)
...       else:
...           global_func_items.append(i)
...
>>> append_loop2([1,2,[3,[4,5]]])
>>> print global_func_items
[1, 2, 3, 4, 5]

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

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