有大量的二維數組轉換為一維的任務,如下的寫法非常的low,性能堪憂。
data = []
for a in alist:
data = data+a
網上搜尋一些方案,但文中未給出性能評測,所以想著做一下測試筆記。省流結論
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]
測試數據如下
%time
import numpy as np
def test_list(n):
return [[i,0] for i in np.arange(n)]
alist = [ test_list(200) for i in np.arange(4000)]
驗證方法1 for
%%time
data =[]
for a in alist:
data = data+a
# CPU times: user 18.1 s, sys: 0 ns, total: 18.1 s
# Wall time: 18.1 s
驗證方法2 列表推導式
%%time
b = [ i for a in alist for i in a]
CPU times: user 28.2 ms, sys: 4.06 ms, total: 32.2 ms Wall time: 31.1 ms
驗證方法3
%%time
import operator
from functools import reduce
mulArrays = alist
bc = reduce(operator.add, mulArrays)
len(bc)
CPU times: user 22.5 s, sys: 599 ms, total: 23.1 s Wall time: 22.1 s
驗證方法4
%%time
from itertools import chain
mulArrays =alist
dc = (list(chain.from_iterable(mulArrays)))
CPU times: user 16.6 ms, sys: 10 µs, total: 16.7 ms Wall time: 16.4 ms
驗證方法5
%%time
mulArrays = alist
mc = sum(mulArrays,[])
CPU times: user 22.3 s, sys: 476 ms, total: 22.8 s Wall time: 21.8 s
結論:
方法耗費時間sum22.8 sitertool,chain16.7msoperator.add23.1sfor 18.1s列表推導式32.2ms參考文章
Python將多維數組轉換為一維_Sunshine_502的博客-CSDN博客_python多維數組轉化為一維數組