程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Performance test of different methods of Python converting multidimensional arrays to one dimension

編輯:Python

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

itertools The fastest

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.2ms

Reference article

Python Convert multidimensional array to one dimension _Sunshine_502 The blog of -CSDN Blog _python Convert multidimensional array into one-dimensional array


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved