学习笔记5—Python 将多维数据转为一维数组 (总结)
- <code class="language-python">import operator
- from functools import reduce
- a = [[1,2,3], [4,6], [7,8,9,8]]
- print(reduce(operator.add, a))
- [1, 2, 3, 4, 6, 7, 8, 9, 8]</code>
-
a = [[1,2,3], [5, 8], [7,8,9]]
-
l=[]
-
for m in range(0,3):
-
for i in a[m]:
-
l.append(i)
-
print(l)
-
[1, 2, 3, 5, 8, 7, 8, 9]
-
from itertools import chain
-
b=[[1,2,3], [5,8], [7,8,9]]
-
c=list(chain(*b))
-
print(c)
-
[1, 2, 3, 5, 8, 7, 8, 9]
-
a=[[1,2,3], [5,8], [7,8,9]]
-
a= eval('['+str(a).replace(' ','').replace('[','').replace(']','')+']')
-
print(a)
-
[1, 2, 3, 5, 8, 7, 8, 9]
-
def flatten(a):
-
if not isinstance(a, (list, )):
-
return [a]
-
else:
-
b = []
-
for item in a:
-
b += flatten(item)
-
return b
-
if __name__ == '__main__':
-
a = [[[1,2],3],[4,[5,6]],[7,8,9]]
-
print(flatten(a))
-
[1, 2, 3, 4, 5, 6, 7, 8, 9]
-
ab = [[1,2,3], [5,8], [7,8,9]]
-
print([i for item in ab for i in item])
-
[1, 2, 3, 5, 8, 7, 8, 9]
2、矩阵转数组:data = [[1,2,3,]] 去掉外层----> data = data[0,:]--->[1,2,3]
3、数组:data = [[1],[2]] ---> data = data.flatten() ---> [1,2]
4、列表:list = [[1],[2]] ---> list1 = [x for [x] in list] ---> list1 = [1,2]
5、将dataframe转成list: data = np.array(data).tolist() (先将dataframe转成矩阵,再将矩阵转成list)