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

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

方法1:flatten

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

方法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"))))
  • 1
  • 2
  • 3
  • 4

方法3:sum()

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

方法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]
  • 1
  • 2
  • 3

方法5:operator

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

方法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]
  • 1
  • 2
  • 3
  • 4

参考博文:
https://leejason.blog.csdn.net/article/details/106928360

你可能感兴趣的:(Python,python,numpy,开发语言)