python - 有效地为数组赋值
问题描述
我如何才能有效地执行此代码?
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 库(没有循环)必须是一种有效的方法。
解决方案
尝试这个 :
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
推荐阅读
- flutter - Flutter:如何从另一个有状态类更新 UI 有状态小部件
- python - Python 抓取数据
- parsing - 使用上下文无关语法来解析期权价差订单字符串?
- macos - 如何在 Mac OS 的 SWT 对话框中访问标签
- reactjs - 我在前端有数据,但在后端未定义
- python - 根据pandas中的公共列值将多个列合并在一起 - python
- python - 带有 id 的 kivymd 参考
- vb.net - 我的 VS2017 Intellisense 发生了什么
- c++ - C++ 二进制文件无法正确读取
- c# - 使用注入到 AspNet Core 的控制器中的类方法