是否存在可列出numpy.ndarray中所有可能坐标的numpy函数?
如何用NumPy生成数组所有可能的坐标
有多种NumPy原生的方式可以实现你需要的功能,以下是具体方案,包括你提供的自定义实现和两种更简洁的原生替代方案:
原自定义实现
import numpy as np def all_possible_coordinates(shape): return np.array([item.ravel() for item in np.meshgrid(*(np.arange(n) for n in shape))]).T def test_all_possible_coordinates(): shape = (1, 2, 2) assert np.all(all_possible_coordinates(shape) == np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1]])) test_all_possible_coordinates()
方案1:使用np.argwhere
利用np.argwhere返回数组所有非零元素坐标的特性,构造指定形状的全1数组即可得到所有可能坐标:
def all_possible_coordinates(shape): return np.argwhere(np.ones(shape))
方案2:使用np.ndindex
np.ndindex会生成遍历指定形状所有坐标的迭代器,将其转换为数组即可得到结果:
def all_possible_coordinates(shape): return np.array(list(np.ndindex(shape)))
内容的提问来源于stack exchange,提问作者edmz
相关产品推荐
相关产品推荐

