Python将二维列表转为一维列表几种方法
pp = [[11,22,33],[111,44,55],[77,88,99]]
将二维列表转为一维列表
1、方法一 列表推导式
ii = [i for p in pp for i in p]
print("ii={}".format(ii)) # ii=[11, 22, 33, 111, 44, 55, 77, 88, 99]
2、方法二flatten,此方法结果输出列表中为空格间隔,且二维列表中必须是相等数量的元素
import numpy as np
n = np.array(pp).flatten()
print("n={}".format(n)) # [ 11 22 33 111 44 55 77 88 99]
3、方法三 sum()
s = sum(pp,[])
print("s={}".format(s)) #s=[11, 22, 33, 111, 44, 55, 77, 88, 99]
4、方法四operator
import operator
from functools import reduce
rr = (reduce(operator.add,pp))
print("rr={}".format(rr)) # rr=[11, 22, 33, 111, 44, 55, 77, 88, 99]
5、方法五itertools
from itertools import chain
it = list(chain.from_iterable(pp))
print("it={}".format(it)) # it=[11, 22, 33, 111, 44, 55, 77, 88, 99]