【发布时间】:2017-10-21 07:16:33
【问题描述】:
参考Why NumPy instead of Python lists?
tom10 说:
速度:这是一个对列表和 NumPy 数组求和的测试,显示 NumPy 数组上的求和快 10 倍(在此测试中,里程可能会有所不同)。
但我的测试使用以下代码:
import numpy as np
import time as time
N = 100000
#using numpy
start = time.time()
array = np.array([])
for i in range(N):
array = np.append(array, i)
end = time.time()
print ("Using numpy: ", round(end-start, 2), end="\n")
#using list
start = time.time()
list = []
for i in range(N):
list.append(i)
list = np.array(list)
end = time.time()
print ("Using list : ", round(end-start, 2), end="\n")
给出结果:
Using numpy: 8.35
Using list : 0.02
使用“append”时,list确实比numpy好?
【问题讨论】:
-
是的,
.append对于list对象是恒定(摊销)恒定时间,对于numpy.ndarray对象是线性时间 -
我有什么办法可以像
list一样做.append到numpy.ndarray? -
Numpy 数组被设计用于保存潜在的多维矩阵,其中附加通常不能像简单的一维情况那样有效。通常在代码中,您会看到 np.zeros(shape) 调用提前分配了足够的元素,您已经知道数据的大小。如果您需要经常追加,您可能应该坚持使用内置列表。
-
人们经常将数据收集到 Vanilla Python 列表中,只有在需要处理时才会生成
numpy.array -
@coldspeed, numpy 列表是对象引用的数组追加是常量,因为列表对象保留的空间比列表中的项目多,因此它可以添加项目而不需要额外的内存。见docs.python.org/2/faq/design.html#how-are-lists-implemented