我想打印从中间切出的列表的一部分
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]
我怎样才能像我想要的那样约束切片?
最佳答案
我记得术语是“clamp”,查了一下,我发现我当然可以这样做
def region_around(lst, index):
return lst[max(0, index-3):index+3]
关于Python 在列表末尾限制切片负界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66676192/