Skip to main content
 首页 » 编程设计

python之在 Python 中创建数组的最快方法

2025年05月04日10thcjp

<分区>

我想用 Python 创建一个 3D 数组,填充 -1。

我测试了这些方法:

import numpy as np 
l = 200 
b = 100 
h = 30 
 
%timeit grid = [[[-1 for x in range(l)] for y in range(b)] for z in range(h)] 
1 loops, best of 3: 458 ms per loop 
 
%timeit grid = -1 * np.ones((l, b, h), dtype=np.int) 
10 loops, best of 3: 35.5 ms per loop 
 
%timeit grid = np.zeros((l, b, h), dtype=np.int) - 1 
10 loops, best of 3: 31.7 ms per loop 
 
%timeit grid = -1.0 * np.ones((l, b, h), dtype=np.float32) 
10 loops, best of 3: 42.1 ms per loop 
 
%%timeit 
grid = np.empty((l,b,h)) 
grid.fill(-1.0) 
100 loops, best of 3: 13.7 ms per loop 

很明显,最后一个是最快的。有人有更快的方法或至少更少的内存占用吗?因为它在 RaspberryPi 上运行。