There are a large number of tasks to convert two-dimensional arrays into one-dimensional arrays , The following expression is very low, Performance is worrying .
data = []
for a in alist:
data = data+a
Search the Internet for some solutions , However, performance evaluation is not given in this paper , So I want to take some test notes . Conclusion of saving flow
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]
The test data are as follows
%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)]
Verification method 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
Verification method 2 List derivation
%%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
Verification method 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
Verification method 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
Verification method 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
Conclusion :
Method Time consuming sum22.8 sitertool,chain16.7msoperator.add23.1sfor 18.1s List derivation 32.2msReference article
Python Convert multidimensional array to one dimension _Sunshine_502 The blog of -CSDN Blog _python Convert multidimensional array into one-dimensional array