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

在Numpy数组广播中,如何传入索引参数生成同形状结果数组?

解决方案

要生成与mylattice形状一致的索引数组,你可以使用numpy.indices()函数,它会直接返回对应维度的索引网格,完美匹配广播需求:

import numpy as np

# 假设 mylattice 是你的二维数组
xindex, yindex = np.indices(mylattice.shape)
sumLattice = getNeighbours(1, 2, mylattice, xindex, yindex)

细节说明

  • np.indices(mylattice.shape)会生成两个二维数组:
    • xindex的每个元素对应原数组中该位置的行索引(即第一个维度的索引)
    • yindex的每个元素对应原数组中该位置的列索引(即第二个维度的索引)
  • 这两个索引数组的形状与mylattice完全相同,传入getNeighbours后,Numpy会自动触发广播机制,对每个位置的索引对(xindex[i,j], yindex[i,j])调用函数,最终生成同形状的sumLattice。

注意事项

如果你的getNeighbours函数原本仅支持单个标量参数(即只能处理单个索引对),需要先用np.vectorize()将其包装为支持向量化操作的函数:

vectorized_getNeighbours = np.vectorize(getNeighbours)
sumLattice = vectorized_getNeighbours(1, 2, mylattice, xindex, yindex)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 13:52:09