python切片的奇怪行为 [英] Strange behavior with python slicing
问题描述
假设我们有以下列表:
>>> a = [x for x in range(10)]
>>> print(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
分别地,两种分割方法都可以按预期进行:
Separately, both ways to slice work as expected:
>>> a[3:8]
[3, 4, 5, 6, 7]
>>> a[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
但是,当结合使用时:
>>> a[3:8:-1]
[]
我希望它是[7, 6, 5 ,4, 3]
或[6, 5, 4, 3, 2]
(如果首先发生反转).
考虑未传递start
或stop
参数时会发生什么,也很有趣:
I would expect it to be [7, 6, 5 ,4, 3]
or perhaps [6, 5, 4, 3, 2]
(if reversing happened first).
It is also interesting to consider what happens when either start
or stop
parameters are not passed:
>>> a[:5:-1]
[9, 8, 7, 6]
这几乎是我所期望的,只有短一点.用numpy
对此进行了测试,它的行为似乎与此相同.
This is almost what I would expect, only its one item short. Tested this with numpy
and it seems to behave in the same way.
这是怎么回事?
推荐答案
使用
a[3:8:-1]
切片的开始和停止位置未根据步长进行调整.负数表示您使它从3向后退,但是没有索引在3到8范围内的元素从3倒数,因此您将获得一个空列表.
The start and stop positions of the slice aren't adjusted based on the step. With a negative step, you're having it go backwards from 3, but there are no elements with indices in the range 3 to 8 counting back from 3, so you get an empty list.
您需要相应地设置开始和停止位置:
You need to set the start and stop accordingly:
a[8:3:-1]
从8倒数到4.
这篇关于python切片的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!