Python 在列表末尾限制切片负界

标签 python python-3.x

我想打印从中间切出的列表的一部分

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/

相关文章:

python - Django Hive 连接

python - 测试 protobuf 消息中是否存在重复字段

python-3.x - 比较 tensorflow variables.index 和 variables.data 文件

python - 在Python中使用math.sqrt(num)比num**0.5有什么优势

python - s3fs 突然停止在 Google Colab 中工作,错误为 "AttributeError: module ' aiobotocore' 没有属性 'AioSession'”

python - 从 jinja 模板中定义默认变量值的明智方法?

python - Python函数的Dask Apply

python - pysimplegui 无按钮文本更新

python-3.x - 为什么这个异常会立即从 asyncio 任务中引发?

Python Lambda 实践