首页 > 解决方案 > 有效地为数组赋值

问题描述

我如何才能有效地执行此代码?

import numpy as np

array = np.zeros((10000,10000)) 
lower = 5000  
higher = 10000 
for x in range(lower, higher): 
    for y in range(lower, higher):
        array[x][y] = 1     
print(array)

我认为使用 numpy 库(没有循环)必须是一种有效的方法。

标签: python

解决方案


尝试这个 :

array[lower:higher, lower:higher] = 1
# OR
array[lower:higher, lower:higher].fill(1) # Faster

当您居住在巨大的阵列中时,第二个过程将比第一个更快。这是使用小规模数据进行的采样时间检查:

>>> from timeit import timeit as t
>>> t("""import numpy as np; a=np.zeros((100,100)); a[50:100,50:100].fill(1)""")
3.619488961998286
>>> t("""import numpy as np; a=np.zeros((100,100)); a[50:100,50:100] = 1""")
3.688145470998279

推荐阅读