1

我有一个列表列表的列表...

A = [ [[1,3]], [[3,5], [4,4], [[5,3]]] ]

以下函数输出[1, 3, 3, 5, 4, 4, 5, 3]

def flatten(a):
    b = []
    for c in a:
        if isinstance(c, list):
            b.extend(flatten(c))
        else:
            b.append(c)
    return b

但是,我想停止在最后一级变平,以便我得到[ [1,3], [3,5], [4,4], [5,3] ]

4

2 回答 2

4

您可以在展平之前测试包含的列表:

def flatten(a):
    b = []
    for c in a:
        if isinstance(c, list) and any(isinstance(i, list) for i in c):
            b.extend(flatten(c))
        else:
            b.append(c)
    return b

演示:

>>> def flatten(a):
...     b = []
...     for c in a:
...         if isinstance(c, list) and any(isinstance(i, list) for i in c):
...             b.extend(flatten(c))
...         else:
...             b.append(c)
...     return b
... 
>>> A = [ [[1,3]], [[3,5], [4,4], [[5,3]]] ]
>>> flatten(A)
[[1, 3], [3, 5], [4, 4], [5, 3]]

这试图在这种情况下尽可能高效;any()只需要测试直到找到一个列表,而不是所有元素。

于 2013-10-27T11:11:58.843 回答
2
A = [ [[1,3]], [[3,5], [4,4], [[5,3]]] ]

print [child[0] if isinstance(child[0], list) else child for item in A for child in item]

输出

[[1, 3], [3, 5], [4, 4], [5, 3]]

注意:此解决方案仅针对此问题。这不是一个通用的列表展平解决方案。

同样的想法,与itertools.chain

from itertools import chain
print [item[0] if isinstance(child[0], list) else item for item in chain(*A)]

输出

[[1, 3], [3, 5], [4, 4], [5, 3]]
于 2013-10-27T11:13:18.087 回答