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

如何实现Python Proxy类在不修改原列表前提下对连续重复元素求和并支持索引访问

实现代码

class Proxy:
    def __init__(self, l):
        self.l = l 

    def __getitem__(self, index):
        if not self.l:
            raise IndexError("Proxy index out of range")
        # 初始化分组统计变量
        current_group = 0
        current_val = self.l[0]
        current_sum = current_val
        # 从第二个元素开始遍历分组
        for num in self.l[1:]:
            if num == current_val:
                current_sum += num
            else:
                # 匹配到目标分组直接返回结果
                if current_group == index:
                    return current_sum
                # 切换到下一个分组
                current_group += 1
                current_val = num
                current_sum = num
        # 遍历结束后检查最后一个分组是否匹配
        if current_group == index:
            return current_sum
        # 所有分组都不匹配说明索引越界
        raise IndexError("Proxy index out of range")

效果验证

用示例输入测试结果完全符合预期,且原列表不会被修改:

>>> l = [0, 1, 1, 1, 0, 2, 2, 2, 0]
>>> proxy = Proxy(l)
>>> proxy[0]
0
>>> proxy[1]
3
>>> proxy[2]
0
>>> proxy[3]
6
>>> proxy[4]
0
>>> l
[0, 1, 1, 1, 0, 2, 2, 2, 0]

实现说明

  • 全程未修改原列表,所有求和逻辑都在__getitem__被调用时实时计算,没有额外做预处理缓存
  • 遍历原列表时累计连续相同元素的和,每遇到不同值就完成一个分组的统计,匹配到目标索引就直接返回结果
  • 索引行为和原生列表保持一致,索引超出分组总数时会抛出标准IndexError异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 15:54:03