有没有很好的方法来切片字典?
N0=5000
N1=10000
N2=10000000
X = np.random.randint(N0,N1, N2) #lost of numbers between N0 and N1
remap = {x:2*x for x in X}
t = time.time()
X_ = [remap[x] for x in X]
print('dict ', time.time()-t)
assert np.all(X_==2*X)
使用numpy切片的第二个选项。但是需要分配X.max()元素
remap = np.arange(N1)*2
t = time.time()
X_ = remap[X]
print('numpy ', time.time()-t)
assert np.all(X_==2*X)
结果:
dict 5.615
numpy 0.285
谢谢