这处理环绕情况
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 答案(列表理解单行)可能会更好
| 归档时间: |
|
| 查看次数: |
2644 次 |
| 最近记录: |