Python 列表可以以二维结构的形式嵌套,作为其他语言中数组的替代品。由于 python 没有数组数据类型,因此它使用列表来创建这些 2d、3d 或有时是 N 维数组。
扁平化是指将二维数组缩减为一维列表的过程。它从嵌套列表中收集所有元素并将它们组合成一个列表。
在 python 中,我们可以通过多种方式将一系列列表转换为一个列表。让我们看看其中一些方法。
如果您想了解有关 Python 中可用的不同数据类型的更多信息,我们为您提供了很棒的课程!
方法一:使用reduce()函数
一个名为 reduce() 的内置函数可用于将二维列表缩减为一个大列表。为了使用reduce()函数,我们必须在程序中导入functools库。
如果您没有安装/更新该库,请 pip install functools
在命令提示符下运行。它是一个包含用于高性能编程的快速工具的库。
此外,concat()
除了该函数之外,还必须使用运算符模块中的 reduce()
函数,以便将子列表连接成一个巨大列表。该concat()
函数必须作为 reduce() 函数的参数传递。
该reduce()
函数接受两个参数:第一个参数定义内部列表的串联,第二个参数是需要减少的所需列表。
让我们看看如何使用该函数将列表列表分解为一个巨大的列表。
#import required modules from functools import reduce from operator import concat #declaring our list lst = [[ 1 , 2 ],[ 3 , 4 ],[ 5 , 6 , 7 ],[ 'bye' , 'hi' ]] print ( "The original list is=" ,lst) #reducing the list flat = reduce (concat,lst) #displaying the flattening of the list print ( "the reduced list is=" ,flat) |
输出是:
The original list is= [[1, 2], [3, 4], [5, 6, 7], [ 'bye' , 'hi' ]] the reduced list is= [1, 2, 3, 4, 5, 6, 7, 'bye' , 'hi' ] |
方法 2:使用嵌套循环
这种方法比前一种方法更加机械。它使用嵌套的 for 循环来一一遍历各个列表,并将每个列表连接成一个巨大的列表。让我们看看如何做到这一点。
lst = [[ "Happy" , "surfing" , "on" ],[ "ask" ],[ "python" ]] #the original 2d list #displaying original list print ( "The original list is =" ,lst) #creating the flattening list flat = [] #nested loop crreation for i in lst: for j in i: flat.append(j) #displaying our results print ( "The flattened list is=" ,flat) |
上面代码的输出将是:
The original list is = [[ 'Happy' , 'surfing' , 'on' ], [ 'ask' ], [ 'python' ]] The flattened list is= [ 'Happy' , 'surfing' , 'on' , 'ask' , 'python' ] |
方法 3:使用列表理解方法
在此方法中,我们将使用列表理解方法使列表更容易展平。只需一行即可完成,因此我们在此示例中获取用户输入。
lst = [] #the original list and the sublists #determining size of list from user input N = int ( input ( "Enter the size of the bigger list=" )) #taking input for i in range (N): size = int ( input ( "Enter the size of " + str (i + 1 ) + " nested list= " )) sublst = [] for j in range (size): inp = input ( "enter the " + str (j + 1 ) + " element of the " + str (i + 1 ) + " nested list= " ) sublst.append(inp) lst.append(sublst) #displaying original list print ( "The original list is =" ,lst) #using list comprehension flat = [element for sublst in lst for element in sublst] #displaying our results print ( "The flattened list is=" ,flat) |
上述代码的输出将是:
Enter the size of the bigger list=2 Enter the size of 1 nested list= 2 enter the 1 element of the 1 nested list= one enter the 2 element of the 1 nested list= two Enter the size of 2 nested list= 2 enter the 1 element of the 2 nested list= three enter the 2 element of the 2 nested list= four The original list is = [[ 'one' , 'two' ], [ 'three' , 'four' ]] The flattened list is= [ 'one' , 'two' , 'three' , 'four' ] |
概括
本教程介绍了将一系列列表扁平化为一个大列表的三种方法。由于资源和内置函数的巨大可用性,在 python 中压平列表非常容易。减少列表的维度有助于提高性能,并且在某些情况下还可以简化计算。列表理解是 Python 编程的重要组成部分。要了解有关 python 列表的更多信息,请访问官方网站。