我想把清单中间剪下来的一部分打印出来。
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]一样
我如何才能像我想要的那样约束切片?
发布于 2021-03-17 23:36:29
我记得术语是“夹子”,查一下它就知道我当然可以这样做。
def region_around(lst, index):
return lst[max(0, index-3):index+3]https://stackoverflow.com/questions/66676192
复制相似问题