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

Python函数right_rounding偶现Index out of range问题求助

排查代码中Index out of range错误的原因

你的代码出现索引越界错误,根源在于当min_vol转换为字符串后不含小数点时,str(min_vol).split('.')只会返回一个元素的列表,此时访问splitted[1]必然触发IndexError。

具体会触发错误的输入场景包括:

  • min_vol是整数类型(比如0、5),转字符串后没有小数点,split结果为["0"]或["5"]
  • min_vol是字符串形式的整数(比如"0"、"10"),split后同样只有单个元素
  • 极端情况:min_vol是其他无法分割出小数点的非预期输入(比如空字符串,但这种情况大概率会被try块捕获,但核心还是无小数点的数字输入)

修复方案示例

可以先判断split后的列表长度,再做后续逻辑:

import traceback
import mt5

def right_rounding(min_vol):
    try:
        min_vol_str = str(min_vol)
        splitted = min_vol_str.split('.')
        if float(splitted[0]) >= 1:
            return 0
        # 先检查是否存在小数部分
        elif len(splitted) >= 2:
            return len(splitted[1])
        # 没有小数部分的情况,返回0或者根据需求调整
        else:
            return 0
    except Exception as e:
        print("Error code =", mt5.last_error())
        print(e, 'error ', traceback.format_exc())

或者用更严谨的方式处理数字的小数部分,比如利用decimal模块来获取精度:

import traceback
import mt5
from decimal import Decimal

def right_rounding(min_vol):
    try:
        d = Decimal(str(min_vol))
        if d >= 1:
            return 0
        # 获取小数部分的长度
        return -d.as_tuple().exponent
    except Exception as e:
        print("Error code =", mt5.last_error())
        print(e, 'error ', traceback.format_exc())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 10:21:38