小书匠python

使用Python脚本的过程中,偶尔需要使用list多层转一层,又总是忘记怎么写搜索关键词,所以总是找了很久,现在把各种方法记录下来,方便自己也方便大家.

方法很多,现在就简单写8种,后面再对这8种方法做基准测试.

声明:文中的方法均收集自Making a flat list out of list of lists in Python


1.定义减层方法

  1. import functools 

  2. import itertools 

  3. import numpy 

  4. import operator 

  5. import perfplot 

  6. from collections import Iterable # or from collections.abc import Iterable 

  7. from iteration_utilities import deepflatten 


  8. #使用两次for循环 

  9. def forfor(a): 

  10. return [item for sublist in a for item in sublist] 


  11. #通过sum 

  12. def sum_brackets(a): 

  13. return sum(a, []) 


  14. #使用functools內建模块 

  15. def functools_reduce(a): 

  16. return functools.reduce(operator.concat, a) 


  17. #使用itertools內建模块 

  18. def itertools_chain(a): 

  19. return list(itertools.chain.from_iterable(a)) 


  20. #使用numpy 

  21. def numpy_flat(a): 

  22. return list(numpy.array(a).flat) 


  23. #使用numpy 

  24. def numpy_concatenate(a): 

  25. return list(numpy.concatenate(a)) 


  26. #自定义函数 

  27. def flatten(items): 

  28. """Yield items from any nested iterable; see REF.""" 

  29. for x in items: 

  30. if isinstance(x, Iterable) and not isinstance(x, (str, bytes)): 

  31. yield from flatten(x) 

  32. else: 

  33. yield x 


  34. def pylangs_flatten(a): 

  35. return list(flatten(a)) 


  36. #使用库iteration_utilities 

  37. def iteration_utilities_deepflatten(a): 

  38. return list(deepflatten(a, depth=1)) 

2.测试

  1. a=[[1,2,3],[4,5,6],[7,8,9]] 

  2. print(a) 


  3. print('--------------------------') 


  4. print(forfor(a)) 

  5. print(sum_brackets(a)) 

  6. print(functools_reduce(a)) 

  7. print(itertools_chain(a)) 

  8. print(numpy_flat(a)) 

  9. print(numpy_concatenate(a)) 

  10. print(pylangs_flatten(a)) 

  11. print(iteration_utilities_deepflatten(a)) 

输出:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

--------------------------

[1, 2, 3, 4, 5, 6, 7, 8, 9]

[1, 2, 3, 4, 5, 6, 7, 8, 9]

[1, 2, 3, 4, 5, 6, 7, 8, 9]

[1, 2, 3, 4, 5, 6, 7, 8, 9]

[1, 2, 3, 4, 5, 6, 7, 8, 9]

[1, 2, 3, 4, 5, 6, 7, 8, 9]

[1, 2, 3, 4, 5, 6, 7, 8, 9]

[1, 2, 3, 4, 5, 6, 7, 8, 9]


2.各种方法的基准测试(消耗时间对比)

各种方法在小数据上消耗时间差别不大,如果数据很小,没必要为了选择而烦恼,如果数据很大,可以参考下面基准测试的结果来选择减层方法.

  1. import matplotlib.pyplot as plt 

  2. from simple_benchmark import benchmark 


  3. #基准测试 

  4. b = benchmark( 

  5. [forfor, sum_brackets, functools_reduce, itertools_chain,numpy_flat, numpy_concatenate, pylangs_flatten,iteration_utilities_deepflatten], 

  6. arguments={2**i: [[0]*5]*(2**i) for i in range(1, 13)}, 

  7. argument_name='number of inner lists' 




  8. #显示测试结果 

  9. plt.subplots(1,1,figsize=(15,10)) 

  10. b.plot() 

  11. plt.legend(loc = 'upper left') 

  12. plt.show() 


消耗时间对比

相同数据量,纵轴方向越小,方法越快.


代码可以从这里下载,需要部署Jupyter环境,可参考我的博客部署方法.

最新文章

  1. [转]学习Nop中Routes的使用
  2. Error writing file‘frm‘(Errcode: 28)
  3. Gitolite配置管理和GIT基本操作
  4. Bootstrap页面布局10 - BS代码
  5. UITabbar的简单操作和实际应用
  6. cojs 简单的数位DP 题解报告
  7. javascript随手记
  8. Mvvm绑定datagrid或listview的selectItems的方法[转]
  9. Selenium IDE整理
  10. ASP.NET MVC 中使用 UEditor 富文本编辑器
  11. C#的输入输出及基本类型
  12. maven修改远程和本地仓库地址
  13. Eclipse 添加 Source 源代码、Javadoc 文档
  14. cocos creator 中的粒子效果
  15. cookie、localStorage、sessionStorage和会话控制机制
  16. openstack(Pike 版)集群部署(八)--- 连接Ceph Cluster 作为后端存储
  17. oracle之 安装 11G RAC 报 NTP failed
  18. Jquery选择器 选择一个不存在的元素 为什么不会返回 false
  19. ip策略路由
  20. 洛谷P2505||bzoj2750 [HAOI2012]道路 && zkw线段树

热门文章

  1. LOJ3146 APIO2019路灯(cdq分治+树状数组)
  2. PowerShell命令批量添加、导出AD用户
  3. .Net MVC 输出HTML内容
  4. 并发编程之Disruptor并发框架
  5. Widget Size and Position !!!!!!!!!!!!!!!!!!
  6. centos下安装nginx(转载)
  7. Protobuf的上手使用
  8. python之变量的数据类型(1)int 、bool 、str 及for循环运用
  9. PHP开发工具 zend studio
  10. 高并发架构系列:Redis并发竞争key的解决方案详解