在 Python 中将嵌套列表转换为平面列表
pythonserver side programmingprogramming更新于 2026/1/13 7:40:17
嵌套列表是其元素本身就是列表的列表。如果我们有一个嵌套列表的 Python 数据容器,有时可能需要将其转换为平面列表,以便可以进一步处理每个元素。
即使是内部元素也可以嵌套。并且可以有很多层嵌套。所以我们将使用递归来解决这个问题。我们将继续检查元素是否嵌套,然后继续一次又一次地应用该函数,直到元素不再是列表。一旦发现元素不是列表,我们将把它附加到一个新列表中,该列表将包含列表中所有非嵌套元素。
示例
listA = [[43, [0]],12, 19, [13,[8, 8]], 21 ]
print('Given nested list:\n', listA)
# Flat List
res = []
# function
def flatlist(l):
for x in l:
if type(x) == list:
flatlist(x)
else:
res.append(x)
flatlist(listA)
print('Flattened List created: \n', res)
输出
运行上述代码得到以下结果 −
Given nested list: [[43, [0]], 12, 19, [13, [8, 8]], 21] Flattened List created: [43, 0, 12, 19, 13, 8, 8, 21]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

