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

如何处理Python中double_index函数的索引过大问题?

处理Python函数double_index索引越界的可行方案

原函数在索引超出列表有效范围时会直接抛出IndexError,以下是几种明确的处理逻辑方案:

方案1:索引合法才修改,否则返回原列表

仅当索引在[0, len(lst)-1]范围内时执行翻倍操作,越界时直接返回原列表,不做任何修改:

def double_index(lst, index):
    if 0 <= index < len(lst):
        lst[index] = lst[index] * 2
    return lst

# 测试越界情况
print(double_index([3, 8, -10, 12], 4))  # 输出: [3, 8, -10, 12]

方案2:索引越界时抛出自定义异常

主动检查索引合法性,越界时抛出更具可读性的自定义异常,让调用方清晰知晓错误原因:

def double_index(lst, index):
    if not (0 <= index < len(lst)):
        raise ValueError("索引超出列表有效范围,请传入0到{}之间的整数".format(len(lst)-1))
    lst[index] = lst[index] * 2
    return lst

# 测试越界情况
print(double_index([3, 8, -10, 12], 4))  # 抛出 ValueError: 索引超出列表有效范围,请传入0到3之间的整数

方案3:正索引越界时自动扩展列表

如果是正索引超过列表长度,将默认值(比如0)翻倍后追加到列表末尾,适合需要自动扩容的场景:

def double_index(lst, index):
    if index < len(lst):
        lst[index] = lst[index] * 2
    elif index >= 0:
        # 可根据需求修改默认值,比如改为空值或其他特定值
        lst.append(0 * 2)
    else:
        # 负索引越界的情况,这里选择不处理,也可按需求调整
        pass
    return lst

# 测试正索引越界
print(double_index([3, 8, -10, 12], 4))  # 输出: [3, 8, -10, 12, 0]

方案4:索引越界时返回特定标记值

不修改原列表,索引无效时返回None或其他标记值,让调用方通过返回值判断操作是否成功:

def double_index(lst, index):
    if 0 <= index < len(lst):
        # 这里返回原列表的副本,避免修改原列表
        new_lst = lst.copy()
        new_lst[index] = new_lst[index] * 2
        return new_lst
    else:
        return None

# 测试调用
result = double_index([3, 8, -10, 12], 4)
if result is None:
    print("索引无效,未执行修改操作")
else:
    print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 20:48:19