You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于曼哈顿距离筛选Numpy二维数组子集且无需遍历迭代?

高效实现方案

基于Numpy的向量化运算即可实现远快于遍历的效果,以下是两种适用不同场景的实现:

通用场景(任意数组尺寸、任意阈值)

直接生成全量坐标网格计算曼哈顿距离,代码简洁易懂:

import numpy as np

# 你的初始数组
my_array = np.zeros((7, 7))
center = (3, 3)  # 中心坐标(行, 列)
threshold = 3    # 曼哈顿距离阈值

# 生成与数组同尺寸的行、列索引网格
i, j = np.indices(my_array.shape)
# 向量化计算所有位置到中心的曼哈顿距离
manhattan_dist = np.abs(i - center[0]) + np.abs(j - center[1])
# 批量赋值符合条件的位置
my_array[manhattan_dist <= threshold] = 1

所有运算都在Numpy底层C层面完成,无Python级循环,性能是逐元素遍历的百倍以上。

大数组小阈值优化场景

如果数组尺寸远大于阈值(比如70x70数组、阈值10),可以只计算中心附近的有效子区域,进一步减少计算量:

import numpy as np

my_array = np.zeros((70, 70))
center = (35, 35)
threshold = 10
h, w = my_array.shape
cy, cx = center

# 计算中心周围有效子区域的边界,避免越界
y_min = max(0, cy - threshold)
y_max = min(h, cy + threshold + 1)
x_min = max(0, cx - threshold)
x_max = min(w, cx + threshold + 1)

# 仅在子区域内计算距离
i_sub, j_sub = np.indices((y_max - y_min, x_max - x_min))
dist_sub = np.abs(i_sub - (cy - y_min)) + np.abs(j_sub - (cx - x_min))

# 给子区域内符合条件的位置赋值
my_array[y_min:y_max, x_min:x_max][dist_sub <= threshold] = 1

这种实现下无论原数组多大,计算量只和阈值正相关,阈值为10时仅需要处理21*21的子区域,开销可以忽略不计。

内容的提问来源于stack exchange,提问作者datum_analyser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 03:15:07