Skip to main content
 首页 » 编程设计

python之在 python 中的列表中拆分列表的元素

2025年05月04日13mfrbuaa

我是 Python 新手。如何从一个列表中的多个列表中创建一个列表?
例如,

list1 = ['aplle', 'grape', ['aplle1', 'grape1'] ] 

输出应该是:

list1 = ['aplle', 'grape', 'aplle1', 'grape1'] 

该列表有数千个元素。

请您参考如下方法:

在compiler.ast中使用flatten:

>>>> from compiler.ast import flatten 
>>>> list1 = ['apple', 'grape', ['apple1', 'grape1', ['apple2', 'grape2'] ] ] 
>>>> flattened_list = flatten(list1) 

输出:
['apple', 'grape', 'apple1', 'grape1', 'apple2', 'grape2']

这将适用于多个嵌套级别

PS:但是这个包已经在Python3中被移除了