如何遍历numpy.array中的嵌套数组并生成指定格式输出
问题解决方法
你当前生成的二维数组是行优先存储的points坐标,想要得到按列拆分的嵌套数组结构,可参考以下两种实现方案:
方案1:基于现有结果快速转换
你原有逻辑输出的all_points是形状为(3,3)的二维数组,直接转置后拆分即可得到目标结构:
# 你原有代码生成的all_points all_points = np.array([[0, 1, 2], [0, 1, 2], [0, 1, 2]]) # 转置后按行提取,指定dtype为object即可 result = [arr.astype(object) for arr in all_points.T]
输出结果完全符合你的需求:
[array([0, 0, 0], dtype=object), array([1, 1, 1], dtype=object), array([2, 2, 2], dtype=object)]
方案2:修改循环逻辑直接生成
如果想在遍历points的过程中直接构造目标结构,可以预先初始化三个列表分别存储X、Y、Z轴坐标,最后统一转为numpy数组:
import numpy as np # 初始化三个空列表分别存三个维度的数值 x_list = [] y_list = [] z_list = [] for i in range(3): x_list.append(points[i].P[0]) y_list.append(points[i].P[1]) z_list.append(points[i].P[2]) # 组装成目标结构 result = [ np.array(x_list, dtype=object), np.array(y_list, dtype=object), np.array(z_list, dtype=object) ]
内容的提问来源于stack exchange,提问作者hp3007
相关产品推荐
相关产品推荐

