0
点赞
收藏
分享

微信扫一扫

Python将列表嵌套结构展平在一行中(两种方法对比)

程序员漫画编程 2022-01-21 阅读 43

Python将列表嵌套结构展平在一行中

1.循环方式

#列表嵌套结构
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flatten_list = []
print(list_of_lists)
#将嵌套结构展开
for x in list_of_lists:
    #取到每一个内层列表
    for y in x:
        flatten_list.append(y)
print(flatten_list)
#[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#[1, 2, 3, 4, 5, 6, 7, 8, 9]

2.列表方式

#列表嵌套结构
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

#展开列表
flatten_lists = [y for x in list_of_lists for y in x]

print(flatten_lists)
#[1, 2, 3, 4, 5, 6, 7, 8, 9]

以上两组程序功能完全一致,最大的区别在于方法2的计算速度比方法1快得多,并且消除了附加调用

举报

相关推荐

0 条评论