我有
numpy.array(n * [value])
记住,但显然这比所有其他建议要慢得多 n .
这里与perfplot(我的宠物项目)进行了全面比较 .
两个 empty 替代品仍然是最快的(使用NumPy 1.12.1) . full 赶上大型数组 .
生成图的代码:
import numpy as np
import perfplot
def empty_fill(n):
a = np.empty(n)
a.fill(3.14)
return a
def empty_colon(n):
a = np.empty(n)
a[:] = 3.14
return a
def ones_times(n):
return 3.14 * np.ones(n)
def repeat(n):
return np.repeat(3.14, (n))
def tile(n):
return np.repeat(3.14, [n])
def full(n):
return np.full((n), 3.14)
def list_to_array(n):
return np.array(n * [3.14])
perfplot.show(
setup=lambda n: n,
kernels=[
empty_fill, empty_colon, ones_times, repeat, tile, full, list_to_array
],
n_range=[2**k for k in range(27)],
xlabel='len(a)',
logx=True,
logy=True,
)