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

如何创建支持索引溢出循环的Pythonic列表?

实现支持循环索引的Python列表

要实现这种索引超出长度时从开头循环取值的列表,最Pythonic的方式是继承原生list类,重写__getitem__方法,通过取模运算将索引映射到列表的有效范围内。

基础实现(支持整数索引)

class CyclicList(list):
    def __getitem__(self, index):
        if isinstance(index, int):
            # 用取模运算统一处理正/负索引
            return super().__getitem__(index % len(self))
        # 非整数索引(如切片)保留原list的默认行为
        return super().__getitem__(index)

测试示例

# 初始化循环列表
l = CyclicList([1, 2, 3, 4, 5])

print(l[7])   # 输出3,7 % 5 = 2,对应原列表索引2的元素
print(l[5])   # 输出1,5 % 5 = 0,对应原列表索引0的元素
print(l[-1])  # 输出5,-1 % 5 = 4,对应原列表索引4的元素
print(l[-6])  # 输出5,-6 % 5 = 4,对应原列表索引4的元素

扩展:支持循环切片(可选)

如果需要让切片也支持循环逻辑,可以进一步扩展__getitem__处理slice对象:

class CyclicList(list):
    def __getitem__(self, index):
        if isinstance(index, int):
            return super().__getitem__(index % len(self))
        elif isinstance(index, slice):
            start, stop, step = index.indices(len(self))
            result = []
            current = start
            # 按步长循环收集元素,直到达到停止位置
            while current < stop:
                result.append(self[current])
                current += step
            return result
        return super().__getitem__(index)

这个实现完全保留了原生list的所有功能,仅在整数索引访问时添加循环映射逻辑,符合Pythonic的设计思路。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 20:45:38