首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python cap切片列表末尾的负界

Python cap切片列表末尾的负界
EN

Stack Overflow用户
提问于 2021-03-17 23:28:57
回答 1查看 33关注 0票数 2

我想把清单中间剪下来的一部分打印出来。

代码语言:javascript
复制
def region_around(lst, index):
    return lst[index-3:index+3]

lst = [i for i in range(10)]
print(region_around(lst, 5)) # correctly prints [2, 3, 4, 5, 6, 7]

print(region_around(lst, 0)) # incorrectly prints []

在第二种情况下,即region_around(lst, 0),我希望使用[0, 1, 2],就好像切片只包含正部分lst[:3]一样

我如何才能像我想要的那样约束切片?

EN

回答 1

Stack Overflow用户

发布于 2021-03-17 23:36:29

我记得术语是“夹子”,查一下它就知道我当然可以这样做。

代码语言:javascript
复制
def region_around(lst, index):
    return lst[max(0, index-3):index+3]
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66676192

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档