扩展列表中的任意数量的子列表

时间:2014-02-05 03:23:43

标签: python

我正在尝试扩展列表中的子列表。我为列表中的一个子列表编写了它。有没有更好的方法来编码,以便扩展任意数量的嵌套列表?参见示例如下:

a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b]

def expand(x):
    # expands a list of lists with no further sublists 
    a = []
    for i in x:
        # could also here do a += i and avoid the second for loop
        for j in i:
            a.append(j)
    return a

print expand(c)

返回所需的[1, 2, 3, 4, 5, 6]

为了进一步澄清,我想知道如何更好地扩展

`e = [c,a,b]'和进一步嵌套的迭代。

3 个答案:

答案 0 :(得分:4)

c = [[1, 2, 3], [4, 5, 6]]

# first method
res = [x for lst in c for x in lst]

# second method
from itertools import chain
res = list(chain(*c))

编辑:他希望迭代嵌套列表!

c = [[[1], [2, 3]], [4, 5], [[6, 7, 8], 9]]

def expand(lst):
    try:
        for a in lst:
            for b in expand(a):
                yield b
    except TypeError:
        yield lst

res = list(expand(c))   # => [1, 2, 3, 4, 5, 6, 7, 8, 9]

答案 1 :(得分:1)

使用递归:

def flat_list(l):
    for a in l:
        if isinstance(a, list):
            for x in flat_list(a):
                yield x
        else:
            yield a

a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b]
e = [c, a, b]

print list(flat_list(c))
print list(flat_list(e))

输出是:

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]

答案 2 :(得分:1)

一个解决方案:

def flatten(ls):
        result = []
        stack = [ls]
        while stack:
            if isinstance(stack[-1], list):
                try: stack.append(stack[-1].pop(0))
                except IndexError: stack.pop() # remove now-empty sublist
            else:
                result.append(stack.pop())
        return result

a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b]
e = [c, a, b]

print flatten(e)

输出:

[1, 2, 3, 4, 5, 6]

或者:

使用sum:

>>> e
[[[1, 2, 3], [4, 5, 6]], [1, 2, 3], [4, 5, 6]]
>>> sum(e[0], [])
[1, 2, 3, 4, 5, 6]

使用reduce:

>>> reduce(lambda x,y: x+y, e[0])
[1, 2, 3, 4, 5, 6]
>>>
相关问题