Numpy與list增減元素對比

2022-10-09 11:24:13 字數 2803 閱讀 8678

都知道numpy可以加快python的運算速度,但是並不是所有地方都快,在元素的增刪方面要遠遠慢於list。看以下例子:

例一:

# list新增元素

l =

start1 = time.time()

print("start:", start1)

for i in range(100000):

end1 = time.time()

print("end", end1)

print("span:", end1 - start1)

# start: 1648979215.742928

# end 1648979215.742928

# span: 0.0

例二:

arr = np.array()

start2 = time.time()

print("start:", start2)

for i in range(100000):

end2 = time.time()

print("end", end2)

print("span:", end2 - start2)

# start: 1648974264.3777995

# end 1648974266.2688227

# span: 1.8910231590270996

例三:

# numpy.hstack()新增元素

arr = np.array()

start2 = time.time()

print("start:", start2)

for i in range(100000):

arr = np.hstack([arr, i])

end2 = time.time()

print("end", end2)

print("span:", end2 - start2)

# start: 1648978917.5062604

# end 1648978919.4940002

# span: 1.9877398014068604

例四:

# list新增行元素

l =

start1 = time.time()

print("start:", start1)

for i in range(100000):

end1 = time.time()

print("end", end1)

print("span:", end1 - start1)

# start: 1648978962.1275697

# end 1648978962.2210128

# span: 0.09344315528869629

例五:

# numpy.vstack()新增行元素

arr = np.zeros(5)

a = np.array([1, 2, 3 ,4, 5])

start2 = time.time()

print("start:", start2)

for i in range(100000):

arr = np.vstack([arr, a])

end2 = time.time()

print("end", end2)

print("span:", end2 - start2)

# start: 1648979036.896138

# end 1648979083.5973537

# span: 46.701215744018555

例六:

# 使用list新增元素後再轉換成numpy

l =

start1 = time.time()

print("start:", start1)

for i in range(100000):

arr = np.array(l)

end1 = time.time()

print("end", end1)

print("span:", end1 - start1)

# start: 1648979211.1942384

# end 1648979211.2098572

# span: 0.01561880111694336

例七:

# list新增行元素後再轉換成numpy

l =

start1 = time.time()

print("start:", start1)

for i in range(100000):

arr = np.array(l)

end1 = time.time()

print("end", end1)

print("span:", end1 - start1)

# start: 1648979279.2713783

# end 1648979279.3811817

# span: 0.10980343818664551

綜上所述,在元素增刪方面,list的效能遠遠好於numpy。但是有些場景確實只能用numpy的,或者用numpy更好的就另說了。

python對list的增加與刪除元素操作

list 增加元素 例項li a b mpilgrim z example li.insert 2,new li a b new mpilgrim z example new li.extend two elements li a b new mpilgrim z example new two e...

如何對list中部分元素排序

直接上 main.h include stdafx.h include datefile.h int tmain int argc,tchar argv datefile.h pragma once include include include include include using name...

numpy陣列與list的轉換 切片與深(淺)拷貝

list元素是一維array的情況 a np.array 1 2 b np.array 5 6,7 c a,b d np.array c 轉換成功 2.list元素是二維array的情況 a np.array 1,2 3,4 b np.array 5,6,7 8,9,10 c a,b d np.ar...