如何在 Python 中扁平化列表?

2023-09-21 21:30:32

在Python中,列表列表(或级联列表)类似于二维数组 - 尽管Python没有像C或Java那样的数组概念。因此,扁平化这样的列表意味着将子列表的元素放入一个类似数组的一维列表中。例如,将列表[[1,2,3],[4,5,6]]展平为[1,2,3,4,5,6]

这可以通过不同的技术来实现,每种技术都解释如下:

使用嵌套循环拼合列表(Flatten List using Nested for Loop)

使用nested for loop将子列表的每个元素追加到平面列表中

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]

使用列表理解展平列表(Flatten List using List Comprehension)

List comprehension技术在单个紧凑语句中给出相同的结果。

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]

使用函子模块的reduce()函数展平列表(Flatten List using the reduce() Function of functools Module)

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]

回想一下,+符号被定义为序列数据类型(listtuplestring)的串联运算符。 除了lambda function,我们还可以使用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]

本文内容总结: