首页 > 解决方案 > 如何在 Python 中添加一个数字来开始和停止切片对象?

问题描述

我阅读了这个关于切片的问题,以便更好地理解 Python 中的切片,但没有发现以简单的方式将切片对象的start和增加stop一个常量。“简单”是指:a)在同一行,b)在一个地方,c)没有额外的变量。

['a', 'b', 'c', 'd', 'e'][0:2]         #works
['a', 'b', 'c', 'd', 'e'][(0:2)+1]     #does not work, what I would find most convenient
['a', 'b', 'c', 'd', 'e'][(0+1):(2+1)] #works, but needs a change at two places
i = 1
['a', 'b', 'c', 'd', 'e'][(0+i):(2+i)] #works but needs an extra line and variable

在切片级别上,slice(0, 2, 1)+1由于"unsupported operand type(s) for +: 'slice' and 'int'". 那么,如何以简单的方式在 Python 中添加一个数字来开始和停止切片对象的参数?

标签: pythonslice

解决方案


为了避免写+i两次,你可以做类似的事情

my_list[i:][:length]

例子:

i = 2
length = 3
print(['0', '1', '2', '3', '4', '5', '6', '7'][i:][:length])

--> output: ['2', '3', '4']

推荐阅读