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

如何将点列表高效转为指定形状的numpy数组(无循环)

解决方案

要实现无循环填充目标数组,核心是利用Numpy的矢量化索引操作,这比Python循环高效得多,尤其适合处理大量点的场景。具体步骤如下:

完整实现代码

import numpy as np

# 原始点列表
points = [(0, 5), (1, 6), (2, 7)]
points_np = np.array(points)

# 计算坐标偏移量(x、y的最小值)
min_coords = points_np.min(axis=0)
# 确定目标数组的形状
target_shape = points_np.max(axis=0) - min_coords + 1

# 创建初始零数组
result_array = np.zeros(target_shape, dtype=int)

# 将原始坐标转换为数组的合法索引(减去最小值偏移)
offset_indices = points_np - min_coords
# 批量赋值:直接通过索引将目标位置设为1
result_array[offset_indices[:, 0], offset_indices[:, 1]] = 1

print(result_array)

输出结果

[[1 0 0]
 [0 1 0]
 [0 0 1]]

关键说明

  • 坐标偏移:原始点的x、y可能不是从0起始,必须减去各自的最小值,才能将点映射到零数组的合法索引范围内(索引从0开始)。比如示例中y的最小值是5,偏移后5→0、6→1、7→2,正好对应数组的列索引。
  • 矢量化索引:result_array[offset_indices[:,0], offset_indices[:,1]] 是Numpy的高级索引用法,一次性选中所有目标位置并赋值,底层由C实现,效率远高于Python循环,点数量越大优势越明显。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 17:05:58