Python中多層List展平為一層


使用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.  
  9. #使用兩次for循環 
  10. def forfor(a): 
  11. return [item for sublist in a for item in sublist] 
  12.  
  13. #通過sum 
  14. def sum_brackets(a): 
  15. return sum(a, []) 
  16.  
  17. #使用functools內建模塊 
  18. def functools_reduce(a): 
  19. return functools.reduce(operator.concat, a) 
  20.  
  21. #使用itertools內建模塊 
  22. def itertools_chain(a): 
  23. return list(itertools.chain.from_iterable(a)) 
  24.  
  25. #使用numpy 
  26. def numpy_flat(a): 
  27. return list(numpy.array(a).flat) 
  28.  
  29. #使用numpy 
  30. def numpy_concatenate(a): 
  31. return list(numpy.concatenate(a)) 
  32.  
  33. #自定義函數 
  34. def flatten(items): 
  35. """Yield items from any nested iterable; see REF.""" 
  36. for x in items: 
  37. if isinstance(x, Iterable) and not isinstance(x, (str, bytes)): 
  38. yield from flatten(x) 
  39. else: 
  40. yield x 
  41.  
  42. def pylangs_flatten(a): 
  43. return list(flatten(a)) 
  44.  
  45. #使用庫iteration_utilities 
  46. def iteration_utilities_deepflatten(a): 
  47. return list(deepflatten(a, depth=1)) 

2.測試

  1. a=[[1,2,3],[4,5,6],[7,8,9]] 
  2. print(a) 
  3.  
  4. print('--------------------------') 
  5.  
  6. print(forfor(a)) 
  7. print(sum_brackets(a)) 
  8. print(functools_reduce(a)) 
  9. print(itertools_chain(a)) 
  10. print(numpy_flat(a)) 
  11. print(numpy_concatenate(a)) 
  12. print(pylangs_flatten(a)) 
  13. 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. #基准測試 
  5. b = benchmark( 
  6. [forfor, sum_brackets, functools_reduce, itertools_chain,numpy_flat, numpy_concatenate, pylangs_flatten,iteration_utilities_deepflatten], 
  7. arguments={2**i: [[0]*5]*(2**i) for i in range(1, 13)}, 
  8. argument_name='number of inner lists' 
  9. ) 
  10.  
  11. #顯示測試結果 
  12. plt.subplots(1,1,figsize=(15,10)) 
  13. b.plot() 
  14. plt.legend(loc = 'upper left') 
  15. plt.show() 

消耗時間對比
消耗時間對比

相同數據量,縱軸方向越小,方法越快.


代碼可以從這里下載,需要部署Jupyter環境,可參考我的博客部署方法.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM