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

Python中通过类实现列表索引越界处理并扩展至批量索引

问题:扩展列表索引越界返回默认值至列表式索引

我现有一段可运行的Python代码,通过继承list类重写__getitem__方法,实现索引越界时返回默认值1000:

import numpy as np

class Set_Value(list):
    def __getitem__(self, index):
        return super(Set_Value, self).__getitem__(index) if index >= 0 and index < len(self) else 1000

A=np.array([100,200,300,400])
S=Set_Value(A)
print(S[1])
print(S[-5])

运行输出符合预期:

  • print1: 200
  • print2: 1000

我希望将此功能扩展至列表式索引,例如:

X=[1,1,1,1,1,1,1,1,1,1]
Y=[1,1,1,-5,-5,-5,1,1,1,1]
print(S[X])
print(S[Y])

期望输出:

  • print1: [200, 200, 200, 200, 200, 200, 200, 200, 200, 200]
  • print2: [200, 200, 200, 1000, 1000, 1000, 200, 200, 200, 200]

我原本想通过类的方式避免使用循环,现在仅希望得到可行的实现方案。


可行实现方案

修改Set_Value类的__getitem__方法,判断传入的索引是否为可迭代对象(非整数/切片类型),若是则遍历每个索引并应用原有的越界处理逻辑,返回结果列表;若为单个索引则保持原有逻辑:

import numpy as np

class Set_Value(list):
    def __getitem__(self, index):
        # 处理列表/可迭代索引的情况
        if not isinstance(index, (int, slice)):
            return [self[idx] for idx in index]
        # 处理单个索引的情况
        if 0 <= index < len(self):
            return super().__getitem__(index)
        else:
            return 1000

# 测试代码
A=np.array([100,200,300,400])
S=Set_Value(A)

print(S[1])          # 输出: 200
print(S[-5])         # 输出: 1000

X=[1,1,1,1,1,1,1,1,1,1]
Y=[1,1,1,-5,-5,-5,1,1,1,1]
print(S[X])          # 输出: [200, 200, 200, 200, 200, 200, 200, 200, 200, 200]
print(S[Y])          # 输出: [200, 200, 200, 1000, 1000, 1000, 200, 200, 200, 200]

逻辑说明

  1. 新增判断:当索引不是整数或切片时,判定为可迭代索引(如列表、元组等),通过列表推导式遍历每个索引,调用自身的__getitem__处理单个索引,最终返回结果列表。
  2. 单个索引的处理逻辑保持不变,越界时返回默认值1000。

注:这里虽然用到了列表推导式(本质是循环),但从代码封装角度,外部调用时无需显式写循环,符合通过类封装功能的思路。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 04:25:18