结束索引为 0 的切片运算符 [重复]
Posted
技术标签:
【中文标题】结束索引为 0 的切片运算符 [重复]【英文标题】:Slice operator with end index 0 [duplicate] 【发布时间】:2019-01-27 06:31:59 【问题描述】:a='0123456789'
>>> a
'0123456789'
>>> a[1:-6:1] # working as expected
'123'
>>> a[2:-1:-1] # i was expecting '210' as answer based on start index=2 end index=0
''
请帮助理解第二个切片运算符如何没有返回任何内容
【问题讨论】:
不可能从 2 递减到 -1,因为这已经接近尾声了。 有一篇非常好的关于python slice的帖子-***.com/questions/509211/… 【参考方案1】:start
和 stop
的负数索引总是通过隐式减去 len(sequence)
进行转换。所以a[2:-1:-1]
翻译成a[2:len(a)-1:-1]
或a[2:9:-1]
,在英文中读作“从索引2 开始,然后向后退1,直到你达到或低于索引9”。
由于您从索引 2 开始,因此您已经在或低于 9,并且切片立即结束。
如果你想从索引切回到字符串的开头,要么省略结束索引(对于负切片意味着继续直到“字符串开头”):
a[2::-1]
或将其显式提供为 None
,这就是省略 stop
最终隐式使用的原因:
a[2:None:-1]
【讨论】:
我对 slice 的理解是 a[start:end-1:step(+ve)] a[start:end+1:step(-ve)] 。这是错误的假设吗? @saidattu:这是一个错误的假设。 Understanding Python's slice notation给出了更完整的解释。【参考方案2】:我想,你想做这样的事情:
a[2::-1] # produces: [2, 1, 0]
使用步骤-1
(您所做的)从2
切片到-1
确实会产生一个空列表,因为您想以负步长向前移动,因此您会收到一个空列表。
This SO post 提供解释:
其实很简单:
a[start:end] # items start through end-1 a[start:] # items start through the rest of the array a[:end] # items from the beginning through end-1 a[:] # a copy of the whole array
还有步长值,可以和上面的任何一个一起使用:
a[start:end:step] # start through not past end, by step
要记住的关键点是 :end 值代表第一个 不在所选切片中的值。所以,结束之间的差异 start 是所选元素的数量(如果 step 为 1,则 默认)。
另一个特点是 start 或 end 可以是负数,这 意味着它从数组的末尾而不是开头开始计数。 所以:
a[-1] # last item in the array a[-2:] # last two items in the array a[:-2] # everything except the last two items
同样,步长可能是负数:
a[::-1] # all items in the array, reversed a[1::-1] # the first two items, reversed a[:-3:-1] # the last two items, reversed a[-3::-1] # everything except the last two items, reversed
如果项目比你要求的少,Python 对程序员很友好 为了。例如,如果您要求 a[:-2] 并且 a 只包含一个 元素,你会得到一个空列表而不是错误。有时你 会更喜欢这个错误,所以你必须意识到这可能会发生。
【讨论】:
我对 slice 的理解是 a[start:end-1:step(+ve)] a[start:end+1:step(-ve)] 。这是错误的假设吗? @saidattu 在这种情况下ve
是什么?
我对 slice 的理解是 a[start:end-1:step(possitive)] a[start:end+1:step(negative)] 。这是错误的假设吗?
@saidattu 我不明白你的具体问题。给定a = [1, 2, 3, 4, 5]
,如果你想从左到右分割一个列表:a[ 0 : 3 : 1 ]
给出[0, 1, 2]
,从右到左a[ 3 : 0 : -1 ]
给出[3, 2, 1]
。如果你想了解更多关于 python 切片的行为,只需打开一个 python 交互式会话并自己测试一下。【参考方案3】:
你可以这样做:
a=[0,1,2,3,4,5,6,7,8,9]
print(a[2::-1])
因为当您在切片操作中执行-1
时(如在您的代码中),python 将其假定为结束索引位置。
为了证明这一点:
>>> a[-1]
9
您的代码格式为:
a[start:end:step]
start
在您的情况下应为 2
(包括),end
应为空白(不包括)。当您将step
指定为-1
时,您以相反的顺序进行切片。
【讨论】:
【参考方案4】:负索引总是被解释为从末尾开始的索引。另一方面,None
总是被解释为“直到适当的结束”:
>>> a[2::-1]
'210'
缺失的索引相当于切片中的None
:
>>> a[2:None:-1]
'210'
要了解我所说的适当结尾是什么意思,请尝试
>>> a[:2:-1]
'9876543'
【讨论】:
【参考方案5】:切片索引如下图所示。切片s[start:end]
是从start
开始并延伸到但不包括end
的元素。所以使用-1
意味着不包括最后一个索引。所以这是按设计工作的。如果想要最后一个索引,可以选择留空。
所以
s[1:]
回你好
s[1:-1]
return ell
请参阅Google Python Class - Strings,它激发了这个答案以及我从哪里抓到了这张照片。
【讨论】:
为什么图片这么大?你能把它缩小到内容的大小吗? 图像已修复.. 我对 slice 的理解是 a[start:end-1:step(+ve)] a[start:end+1:step(-ve)] 。这是错误的假设吗? -ve 的 +ve 步骤改变了切片字符串的方向..它绝不会改变项目的范围....项目的范围仍然保持 start以上是关于结束索引为 0 的切片运算符 [重复]的主要内容,如果未能解决你的问题,请参考以下文章
python运算学习之Numpy ------ 数组的切片索引与循环遍历条件和布尔数组