为什么我在 Python 中的负切片不起作用? [英] Why does my negative slicing in Python not work?
问题描述
我是 Python 新手,已经阅读了一些关于切片的教程,但是我在空闲时运行的示例似乎没有返回我期望的结果.例如,我已将以下列表分配给变量 a
I am new to Python and have read several tutorials on slicing however the examples I run in idle don't seem to return what I expect it to. For example I have assigned the follow list to the variable a
a=[0,1,2,3,4,5,6,7,8,9]
现在我将切片理解为 [number I want to include:number up to and don't want to include:step]
因此,如果我执行 a[1]
,我会期望 1
.如果我做 a[1:3]
,它会是 1,2
Hence if I do a[1]
, I would expect 1
. If I do a[1:3]
, it would be 1,2
现在如果我做 a[-1]
,我得到 9
但是如果我做 a[-1:-5]
,我什么也得不到.我看到的只是[]
.这是为什么?我希望看到 9,8,7,6
Now if I do a[-1]
, I get 9
BUT if I do a[-1:-5]
, I get nothing. All I see is []
. why is that? I would expect to see 9,8,7,6
我在 Windows 7 Professional 上运行 Python 2.7
I am running Python 2.7 on Windows 7 Professional
推荐答案
在这种情况下,您需要添加 step
参数以获得您想要的:
In this case, you would need to add in the step
argument in order to get what you want:
In [1]: a=[0,1,2,3,4,5,6,7,8,9]
In [2]: a[-1:-5:-1]
Out[2]: [9, 8, 7, 6]
如果你想节省更多的空间,你可以省略第一个参数:
And if you want to save a bit more space, you can omit the first argument:
In [3]: a[:-5:-1]
Out[3]: [9, 8, 7, 6]
Python 处理负"切片的方式是将对象的 len
添加到负数.因此,当您说 In a[-1:-5]
时,它基本上是在说 a[(-1+10):(-5+10)]
,即等于 a[9:5]
,并且由于 start
/end
指的是两者之间的所有字符(在列表中向前"移动),它不会返回任何内容(因此是您的空白列表).您可以通过执行以下操作来查看这一点:
The way that Python handles the 'negative' slices is that it adds then len
of the object to the negative number. So when you say In a[-1:-5]
, it is basically saying a[(-1+10):(-5+10)]
, which equals a[9:5]
, and since start
/end
refers to all characters between the two (moving 'forward' through the list), it doesn't return anything (hence your blank list). You can see this by doing something like:
In [5]: a[-5:9]
Out[5]: [5, 6, 7, 8]
In [6]: a[5:9]
Out[6]: [5, 6, 7, 8]
使用负索引和正索引得到相同的结果,因为 -5 + 10 = 5
.
You get the same result with the negative and positive indices, since -5 + 10 = 5
.
提供 -1 step
参数告诉它从第一个元素开始,但从开始位置向后移动.
Providing the -1 step
argument tells it to start at the first element but move backwards from the start position.
这篇关于为什么我在 Python 中的负切片不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!