Python将二维数组/多维数组转换为一维

Python将二维数组/多维数组转换为一维

  • 方法1:flatten
  • 方法2:reshape+concatenate
  • 方法3:sum()
  • 方法4:列表推导式
  • 方法5:operator
  • 方法6:itertools

方法1:flatten

import numpy as np
mulArrays = [[1,2,3],[4,5,6],[7,8,9]]
print(list(np.array(mulArrays).flatten()))

方法2:reshape+concatenate

import numpy as np
mulArrays = [[1,2,3],[4,5,6],[7,8,9]]
print(list(np.concatenate(array.reshape((-1,1),order="F"))))

方法3:sum()

mulArrays = [[1,2,3],[4,5,6],[7,8,9]]
print(sum(mulArrays,[])) #[1, 2, 3, 4, 5, 6, 7, 8, 9]

方法4:列表推导式

mulArrays = [[1,2,3],[4,5,6],[7,8,9]]
print([i for arr in mulArrays for i in arr]) #[1, 2, 3, 4, 5, 6, 7, 8, 9]

方法5:operator

import operator
from functools import reduce
mulArrays = [[1,2,3],[4,5,6],[7,8,9]]
print(reduce(operator.add, mulArrays))

方法6:itertools

from itertools import chain
mulArrays = [[1,2,3],[4,5,6],[7,8,9]]
print(list(chain.from_iterable(mulArrays))) #[1, 2, 3, 4, 5, 6, 7, 8, 9]

转载请注明转自:https://leejason.blog.csdn.net/article/details/106928360

你可能感兴趣的:(Python,二维数组转一维)