Skip to main content
 首页 » 编程设计

python之在列表中扩展任意数量的子列表

2025年05月04日17wuhuacong

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

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]' 和进一步的嵌套迭代。

请您参考如下方法:

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]