Numpy与list增减元素对比

Numpy与list增减元素对比

都知道Numpy可以加快Python的运算速度,但是并不是所有地方都快,在元素的增删方面要远远慢于list。看以下例子:

例一:

# list添加元素
l = []
start1 = time.time()
print("Start:", start1)
for i in range(100000):
    l.append(i)
end1 = time.time()
print("End", end1)
print("Span:", end1 - start1)

# Start: 1648979215.742928
# End 1648979215.742928
# Span: 0.0

例二:

# numpy.append()添加元素
arr = np.array([])
start2 = time.time()
print("Start:", start2)
for i in range(100000):
    arr = np.append(arr, i)
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):
    l.append([1, 2, 3, 4, 5])
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):
    l.append(i)
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):
    l.append([1, 2, 3, 4, 5])
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更好的就另说了。

posted @ 2022-04-03 17:59  凡璞  阅读(109)  评论(0编辑  收藏  举报
1 2
3 4
5 6