-
将python列表中的多个列表转化为一个列表:列表的扁平化处理总结
方法一: 使用 itertools
# 速度最快 import itertools a = [[1, 2, 3, 4], [4, 4, 5, 6], [7], [7, 8, 9]] out = list(itertools.chain.from_iterable(a)) print(out) output:[1, 2, 3, 4, 4, 4, 5, 6, 7, 7, 8, 9]
方法二: 使用 sum() 函数
a = [[1, 2, 3, 4], [4, 4, 5, 6], [7], [7, 8, 9]] out = sum(a, []) print(out) output:[1, 2, 3, 4, 4, 4, 5, 6, 7, 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]