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

遍历numpy数组仅返回最后一项,正弦导航控制函数输出异常如何解决

问题原因分析
  • 循环逻辑错误:你写的for steering in vec_steering:每次遍历都把steering赋值为当前的单个数值,循环结束后steering只保留vec_steering的最后一个元素,所以最终只返回了最后一组值(1023, 1050)
  • 变量名冲突:开头定义的steering = []是用于存储序列的列表,但循环变量也用了steering,直接覆盖了原本的列表变量,导致序列值根本没有被存储
  • 冗余代码问题:np.vectorize(np.int)没有必要,直接用数组自带的astype(int)方法转换类型性能更高
修正后的代码
import numpy as np

def stop():
    steering = 1024
    throttle = 1024
    return steering, throttle

def case2():
    # 定义列表存储所有steering、throttle组合
    result = []
    time_interval = 5
    samples = 50
    t = np.linspace(0, time_interval, samples)
    time_req = 5.0
    A = 900
    vec_steering = A*np.sin(2*(np.pi)*t/time_req) + 1024
    # 转换为整数类型
    vec_steering = vec_steering.astype(int)
    throttle = 1050
    # 遍历所有steering值,组合后存入列表
    for s in vec_steering:
        result.append((s, throttle))
    # 返回整个序列列表
    return result
验证方法

调用case2()后遍历返回的列表即可得到你期望的所有值:

for item in case2():
    print(item)

输出结果和你给出的正弦序列完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 04:15:03