学习笔记5—Python 将多维数据转为一维数组 (总结)

[python] view plain copy
  1. <code class="language-python">import operator  
  2. from functools import reduce  
  3. a = [[1,2,3], [4,6], [7,8,9,8]]  
  4. print(reduce(operator.add, a))  
  5. [1, 2, 3, 4, 6, 7, 8, 9, 8]</code>  

 

  1. a = [[1,2,3], [5, 8], [7,8,9]]
  2. l=[]
  3. for m in range(0,3):
  4. for i in a[m]:
  5. l.append(i)
  6. print(l)
  7. [1, 2, 3, 5, 8, 7, 8, 9]

 

  1. from itertools import chain
  2. b=[[1,2,3], [5,8], [7,8,9]]
  3. c=list(chain(*b))
  4. print(c)
  5. [1, 2, 3, 5, 8, 7, 8, 9]
  1. a=[[1,2,3], [5,8], [7,8,9]]
  2. a= eval('['+str(a).replace(' ','').replace('[','').replace(']','')+']')
  3. print(a)
  4. [1, 2, 3, 5, 8, 7, 8, 9]

 

  1. def flatten(a):
  2. if not isinstance(a, (list, )):
  3. return [a]
  4. else:
  5. b = []
  6. for item in a:
  7. b += flatten(item)
  8. return b
  1. if __name__ == '__main__':
  2. a = [[[1,2],3],[4,[5,6]],[7,8,9]]
  3. print(flatten(a))
  4. [1, 2, 3, 4, 5, 6, 7, 8, 9]

 

  1. ab = [[1,2,3], [5,8], [7,8,9]]
  2. print([i for item in ab for i in item])
  3. [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)

posted @ 2018-08-30 00:48  何弈  阅读(8794)  评论(0编辑  收藏  举报
你好