时间:2022-03-21 09:28:11 | 栏目:Python代码 | 点击:次
方法一:使用列表推导式
>>> 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]