Python,遍历范围内的列表

jus*_*hap 1 python

我有一个值为 0 到 30 的列表。

如何使用添加的偏移量遍历这些值(在一个范围内)?

由于这可能没有任何意义,我做了一个小图:

图表

ent*_*opy 5

这处理环绕情况

def list_range(offset, length, l):
    # this handles both negative offsets and offsets larger than list length
    start = offset % len(l)
    end = (start + length) % len(l)
    if end > start:
        return l[start:end]
    return l[start:] + l[:end]
Run Code Online (Sandbox Code Playgroud)

编辑:我们现在处理负索引情况。

编辑 2:交互式 shell 中的示例用法。

>>> l = range(30)
>>> list_range(15,10,l)
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
>>> list_range(25,10,l) # I'm guessing the 35 in the example was accidental
[25, 26, 27, 28, 29, 0, 1, 2, 3, 4]
>>> list_range(-8,10,l)
[12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
Run Code Online (Sandbox Code Playgroud)

编辑 3:更新以忽略每个评论的 -8,10 案例

编辑 4:我使用列表切片是因为我怀疑它们比循环数据更有效。我刚刚测试了它,我的预感是正确的,它比循环列表的 mVChr 版本快大约 2 倍。但是,这可能是一个过早的优化,在您的情况下,更多的 Pythonic 答案(列表理解单行)可能会更好