如何在 Python 中展平列表中的列表?
在 Python 中,列表中的列表(或级联列表)类似于二维数组——尽管 Python 没有像 C 或 Java 中那样的数组概念。因此,展平这样的列表中的列表意味着将子列表的元素放入一维数组般的列表中。例如,列表 [[1,2,3],[4,5,6]]
被展平为 [1,2,3,4,5,6]
。
这可以通过不同的技术实现,每种技术都将在下面解释。
使用嵌套 for 循环展平列表
使用嵌套 for 循环将子列表的每个元素添加到展平的列表中。
示例
nestedlist = [ [1, 2, 3, 4], ["Ten", "Twenty", "Thirty"], [1.1, 1.0E1, 1+2j, 20.55, 3.142]] flatlist=[] for sublist in nestedlist: for element in sublist: flatlist.append(element) print(flatlist)
输出
[1, 2, 3, 4, 'Ten', 'Twenty', 'Thirty', 1.1, 10.0, (1+2j), 20.55, 3.142]
使用列表推导展平列表
列表推导技术在一个紧凑的语句中给出相同的结果。
示例
nestedlist = [ [1, 2, 3, 4], ["Ten", "Twenty", "Thirty"], [1.1, 1.0E1, 1+2j, 20.55, 3.142]] flatlist=[element for sublist in nestedlist for element in sublist] print(flatlist)
输出
[1, 2, 3, 4, 'Ten', 'Twenty', 'Thirty', 1.1, 10.0, (1+2j), 20.55, 3.142]
使用 functools 模块的 reduce() 函数展平列表
reduce() 函数的第一个参数本身是一个带有两个参数的函数,第二个参数是一个列表。参数函数累积地应用于列表中的元素。例如,reduce(lambda a,b:a+b, [1,2,3,4,5])
返回列表中数字的累积和。
示例
from functools import reduce flatlist = reduce(lambda a,b:a+b, nestedlist) print(flatlist)
输出
[1, 2, 3, 4, 'Ten', 'Twenty', 'Thirty', 1.1, 10.0, (1+2j), 20.55, 3.142]
回想一下,+
符号被定义为序列数据类型(列表、元组和字符串)的连接运算符。除了lambda 函数,我们还可以使用 operator
模块中定义的 concat()
函数作为参数,以累积方式附加子列表以进行展平。
示例
from functools import reduce from operator import concat nestedlist = [ [1, 2, 3, 4], ["Ten", "Twenty", "Thirty"], [1.1, 1.0E1, 1+2j, 20.55, 3.142]] flatlist = reduce(concat, nestedlist) print(flatlist)
输出
[1, 2, 3, 4, 'Ten', 'Twenty', 'Thirty', 1.1, 10.0, (1+2j), 20.55, 3.142]