一、使用sum()函数,可展开两层的嵌套列表
a = [[1, 2, 3], [ 4, 5, 6], [7], [8, 9]] out = sum(a, []) print(out) output:[1, 2, 3, 4, 5, 6, 7, 8, 9]
二、使用itertools
import itertools a = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] out = list(itertools.chain.from_iterable(a)) print(out) output:[1, 2, 3, 4, 5, 6, 7, 8, 9]
三、使用operator、reduce函数
import operator from functools import reduce a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(reduce(operator.add, a)) a:[1, 2, 3, 4, 5, 6, 7, 8, 9]
上面方法可能只对二层列表有效,如果无法确定嵌套深度,有如下的方法:
四、可以使用递归函数来解决(万能方式)
data = [[[1],[2],[3]],[4,5],[[[[[[6]]]]]]] print(data) result = [] def take_out(arr): for item in arr: if isinstance(item,int): result.append(item) else: take_out(item) take_out(data) print(result) out:[[[1], [2], [3]], [4, 5], [[[[[[6]]]]]]] [1, 2, 3, 4, 5, 6]
五、使用标准库itertools中的chain()函数
from itertools import chain from copy import deepcopy data = [[[1],[2],[3]],[[4],[5],[6]]] print(data) result = deepcopy(data) while True: result = list(chain(*result)) if isinstance(result[0], int): break print(result) [[[1], [2], [3]], [[4], [5], [6]]] [1, 2, 3, 4, 5, 6]
六、扩展库numpy
import numpy as np data = [[[1],[2],[3]],[[4],[5],[6]]] print(data) temp_data = np.array(data) a = list(temp_data.reshape(temp_data.size,)) print(a) [[[1], [2], [3]], [[4], [5], [6]]] [1, 2, 3, 4, 5, 6]