Python - 提取最内层列表

Roi*_*Tal 23 python python-2.7

刚刚开始玩Python,请耐心等待:)

假设以下列表包含嵌套列表:

[[[[[1, 3, 4, 5]], [1, 3, 8]], [[1, 7, 8]]], [[[6, 7, 8]]], [9]]
Run Code Online (Sandbox Code Playgroud)

用不同的表示形式:

[
    [
        [
            [
                [1, 3, 4, 5]
            ], 
            [1, 3, 8]
        ], 
        [
            [1, 7, 8]
        ]
    ], 
    [
        [
            [6, 7, 8]
        ]
    ], 
    [9]
]
Run Code Online (Sandbox Code Playgroud)

您将如何提取这些内部列表,以便返回具有以下表单的结果:

[[1, 3, 4, 5], [1, 3, 8], [1, 7, 8], [6, 7, 8], [9]]
Run Code Online (Sandbox Code Playgroud)

非常感谢!

编辑(谢谢@falsetru):

空内部列表或混合类型列表永远不会成为输入的一部分.

tob*_*s_k 33

这似乎有效,假设没有'混合'列表,如[1,2,[3]]:

def get_inner(nested):
    if all(type(x) == list for x in nested):
        for x in nested:
            for y in get_inner(x):
                yield y
    else:
        yield nested
Run Code Online (Sandbox Code Playgroud)

产量list(get_inner(nested_list)):

[[1, 3, 4, 5], [1, 3, 8], [1, 7, 8], [6, 7, 8], [9]]
Run Code Online (Sandbox Code Playgroud)

甚至更短,没有生成器,sum用于组合结果列表:

def get_inner(nested):
    if all(type(x) == list for x in nested):
        return sum(map(get_inner, nested), [])
    return [nested]
Run Code Online (Sandbox Code Playgroud)


fal*_*tru 13

使用itertools.chain.from_iterable:

from itertools import chain

def get_inner_lists(xs):
    if isinstance(xs[0], list): # OR all(isinstance(x, list) for x in xs)
        return chain.from_iterable(map(get_inner_lists, xs))
    return xs,
Run Code Online (Sandbox Code Playgroud)

用来isinstance(xs[0], list)代替all(isinstance(x, list) for x in xs),因为没有混合列表/空内部列表.


>>> list(get_inner_lists([[[[[1, 3, 4, 5]], [1, 3, 8]], [[1, 7, 8]]], [[[6, 7, 8]]], [9]]))
[[1, 3, 4, 5], [1, 3, 8], [1, 7, 8], [6, 7, 8], [9]]
Run Code Online (Sandbox Code Playgroud)


use*_*064 5

比递归更有效:

result = []
while lst:
    l = lst.pop(0)
    if type(l[0]) == list:
        lst += [sublst for sublst in l if sublst] # skip empty lists []
    else:
        result.insert(0, l) 
Run Code Online (Sandbox Code Playgroud)

  • 从列表中删除第一项,插入列表的开头需要O(n)时间.使用[`collections.deque`](http://docs.python.org/2/library/collections.html#collections.deque)可以提高速度.见http://ideone.com/RFGhnh (4认同)
  • 如果您声称您的解决方案比其他解决方案更有效,请附加小型和大型输入的基准.请参阅falsetru的评论,为什么它很慢. (2认同)