方法一:使用列表推导式
>>> vec = [[1,2,3],[4,5,6],[7,8,9]] >>> get = [num for elem in vec for num in elem] >>> get [1, 2, 3, 4, 5, 6, 7, 8, 9]
方法相当于
>>> vec = [[1,2,3],[4,5,6],[7,8,9]] >>> result = [] >>> for elem in vec: for num in elem: result.append(num) >>> result [1, 2, 3, 4, 5, 6, 7, 8, 9]
方法二:
使用sum函数
>>> vec = [[1,2,3],[4,5,6],[7,8,9]] >>> get = sum(vec,[]) >>> get [1, 2, 3, 4, 5, 6, 7, 8, 9]
或者是使用chain函数
>>> vec = [[1,2,3],[4,5,6],[7,8,9]] >>> from itertools import chain >>> list(chain(*vec)) [1, 2, 3, 4, 5, 6, 7, 8, 9]
以上这篇python实现嵌套列表平铺的两种方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持找一找教程网。