简体   繁体   English

反向切片Python

[英]Slicing Python in Reverse

In Python I know you can slice sequences as seq[from:to+1:step]. 在Python中,我知道您可以将序列切片为seq [from:to + 1:step]。 But if you slice in reverse, using a step of -1, why does it not show the from element? 但是,如果使用-1步反向切片,为什么不显示from元素呢? It shifts one element to the right from what I would expect. 它将一个元素从我期望的位置向右移。

x="012345"
x[4:2:-1] 

prints 43, rather than 4321 as I expected. 打印43,而不是我预期的4321。 So if step is -1 then it prints seq[from:to-1:step]. 因此,如果step为-1,那么它将打印seq [from:to-1:step]。 Seems inconsistent. 似乎不一致。

If you want to slice down to 4321 you should do x[-2:0:-1] . 如果要切成4321,应该执行x[-2:0:-1]

This means to start from -2 (-1 is the last element) and go to 0 (nothing is the first element) with -1 as step. 这意味着从-2开始(-1是最后一个元素),然后以-1作为步长到0(什么都不是第一个元素)。

It works as expected. 它按预期工作。
If you need your result, 如果您需要结果,

>>> x[4:0:-1]
'4321'

This means, start slicing from 5th element and go till 1st element(but not including it). 这意味着,从第5个元素开始切片,直到第1个元素(但不包括它)。 This kind of slicing works only if you specify the step size to be negative. 仅当您将step size指定为负数时,这种切片才有效。

So in general, follow olofom's answer. 因此,通常,请遵循olofom的回答。

Slicing goes from the first number (inclusive) to the second number (exclusive) with a step of the third number. 切片从第一个数字(含)到第二个数字(不含),步长为第三个数字。 In your case, the first number accesses "4" and the second number accesses "2". 在您的情况下,第一个数字访问“ 4”,第二个数字访问“ 2”。 With a step of -1, it will start with the character at the position of the first number ("4"), and then get the next character (or with a step of -1, actually the previous character "3"), but will stop there because the second index (2) is exclusive. 以-1为步长,它将以第一个数字(“ 4”)处的字符开始,然后得到下一个字符(或以-1的步长,实际上是前一个字符“ 3”),但由于第二个索引(2)是互斥的,因此将在此处停止。 To get everything from "4" to "0", you can do x[4:0:-1] or, more conveniently, x[:5] . 要获得从“ 4”到“ 0”的所有内容,可以执行x[4:0:-1]或更方便地执行x[:5]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM