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

如何实现NumPy固定数组的遍历与追加,得到与Range一致的结果?

问题:用固定数组替代Range实现等价操作的误区与解决方法

已实现的Range处理代码及期望输出

这是目前可用的基于Range的处理逻辑,能得到预期输出:

# 当前可用代码 & 期望输出

degrees = np.arange(10,50,10)
ITER = np.array(degrees)
for i in range(4): 
    x1 = np.sin(np.radians(ITER))
    y1 = np.cos(np.radians(ITER ))
XY = np.column_stack((np.asarray(x1),np.asarray(y1)))
print(XY)

错误尝试:数组追加始终为空

尝试用固定数组实现时,无论怎么操作,最终数组都为空,显然存在错误假设:

# 多次尝试数组追加都失败了
# 输出的数组始终为空,肯定有错误假设
xy1 = np.array([])
degrees = np.array([10, 20, 30, 40])
for degree in np.nditer(degrees):
    x1 = np.sin(np.radians(degree))
    y1 = np.cos(np.radians(degree))
    # np.append(xy1,[x1,y1]).reshape(2,1)
    # ugh = np.asarray([x1,y1])
    # a = np.append(xy1,[[x1,y1]],axis =0).reshape(2,-1)
    # a = np.append(xy1,[[x1],[y1]],axis =0)#.reshape(2,-1)
    # np.append(xy1,ugh, axis =0).reshape(2,1)
    # np.append(xy1,ugh, axis =0)
    # a = np.append(xy1,[ugh])
XY = np.column_stack((np.asarray(x1),np.asarray(y1)))
print(xy1)

# 期望输出与上面可用代码的结果一致

反思

事后想想其实用列表就能解决,但我想把这个问题当成numpy数组操作的学习机会。

@hpaulj提供的解决方案

# 基于Range的实现
degrees = np.arange(10,50,10)
x1 = np.sin(np.radians(degrees))
y1 = np.cos(np.radians(degrees ))
XY = np.column_stack((x1, y1))

# 基于固定列表的实现
degrees = np.array([10, 20, 30, 40])
XY = np.zeros((0,2))
for rad in np.radians(degrees):
    XY = np.append(XY, [[np.sin(rad), np.cos(rad)]], axis=0)

自我修正:修复数组初始化形状错误

我主要的错误是数组初始化时形状不正确,修正后的代码如下:

XY = np.zeros((0,2))
degrees = np.array([10, 20, 30, 40])
for rads in np.radians(degrees):
    x1 = np.sin(rads)
    y1 = np.cos(rads)
    XY = np.append(XY, [[x1,y1]]).reshape(-1,2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:35:17