Skip to main content
 首页 » 编程设计

python之将列表列表分解为具有不可迭代列表元素的单个列表

2025年05月04日13zhoujg

引用: python decompose a list Flattening a shallow list in Python

虽然上述解决方案很有帮助,但我的问题略有不同,我想知道是否有 pythonic 方法来解决它。

a = [['a-3','b-3'],'r',['j']] 

我想要的是一种使“a”等于以下内容的简洁方法:

a = ['a-3','b-3','r','j'] 

我一直在使用 python 2.4,因此兼容 2.4 的 pythonic 解决方案会很棒,但我仍然会发现 2.7+ 示例也很有趣。

主要问题是存在不可迭代的元素,否则 sum(lst,[]) 工作得很好,2.7+ 的 chain 方法也是如此

请您参考如下方法:

Pythonic 解决方案可能意味着很多事情。用readability counts (PEP 20) 请记住,这是我对该主题的贡献:

def dec(input_, output_): 
    if type(input_) is list: 
        for subitem in input_: 
            dec(subitem, output_) 
    else: 
        output_.append(input_) 

例子:

input_ = [['a-3','b-3', ['x','hello', ['3','b']]],'r',['j']] 
output_ = ['a-3', 'b-3', 'x', 'hello', '3', 'b', 'r', 'j']