Python将多维数组转换为一维

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

分类专栏: Python 文章标签: 二维数组转一维

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

方法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]

你可能感兴趣的:(机器学习算法基础,python,数据挖掘)