如何在Python中展平浅列表

如何在Python中展平浅列表?

一个简单而直接的解决方案是使用两个嵌套的for循环将子列表中的项添加到平坦列表中。

lst = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]
flatlist = []
for sublist in lst:
   for item in sublist:
      flatlist.append(item)
print (flatlist)

更紧凑且Pythonic的解决方案是使用itertools模块中的chain()函数。

>>> lst  =[[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]
>>> import itertools
>>> flatlist = list(itertools.chain(*lst))
>>> flatlist
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]

阅读更多:Python 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程