简体   繁体   English

Python 理解切片符号题

[英]Python understanding slice notation question

I know that there are a lot of slice notation questions but I think this should work but it doesn't.我知道有很多切片符号问题,但我认为这应该有效,但它没有。 Say we have:假设我们有:

a = [1, 2, 3, 4]

Let's say we want to reverse subarray from index 0 to 1:假设我们要将子数组从索引 0 反转为 1:

a = a[1:-1:-1] + a[2:] 

I would expect to get a=[2, 1, 3, 4] but what I get is a = [3, 4]我希望得到a=[2, 1, 3, 4]但我得到的是a = [3, 4]

Why is that?这是为什么? Why doesn't a[1:-1:-1] return [2, 1] ?为什么a[1:-1:-1]不返回[2, 1] Am I missing something?我错过了什么吗?

When slicing with a negative step (Eg. list_[a, b, -n] ), a will be the inclusive index to start from, b will be the index to go up to without including it (hence exclusive) while taking steps of size n towards the left.当使用负步骤(例如list_[a, b, -n] )进行切片时, a将是开始的包含索引, b将是 go 的索引,直到不包括它(因此是唯一的),同时采取步骤大小n向左。 That's how slicing works with negative steps.这就是切片与负步骤一起工作的方式。

Try this:尝试这个:

a = [1, 2, 3, 4]
a = a[1::-1] + a[2:] 
print(a)
# Out: [2, 1, 3, 4]

Note: if you slice as a[1:0:-1] , then the element at index zero is not included due to slicing rules.注意:如果您切片为a[1:0:-1] ,则由于切片规则,索引为零的元素不包括在内。 Hence you have to omit that index to tell python to keep including elements till you run out of elements.因此,您必须省略该索引来告诉 python 继续包含元素,直到您用完元素。

If this sort of slicing confuses you, the simpler way would be to do:如果这种切片让你感到困惑,更简单的方法是:

a = a[:2][::-1] + a[2:]  # take normal slice first, then reverse it

Edit: Your a[1:-1:-1] logic is flawed because -1 is the index of the last element of the list (negative indexing exists,).编辑:您a[1:-1:-1]逻辑有缺陷,因为 -1 是列表最后一个元素的索引(存在负索引)。 so you can't use math and argue that -1 is one less than 0 so it should work.所以你不能使用数学并争辩说 -1 比 0 小一,所以它应该可以工作。

Here is a what your code is doing:这是您的代码正在执行的操作:

You have a list a=[1,2,3,4]你有一个列表a=[1,2,3,4]

Now when you do a[1:-1:-1] , it will return a [] .现在,当您执行a[1:-1:-1]时,它将返回一个[] That is because list slicing work: [start index: end index: steps] .那是因为列表切片工作: [start index: end index: steps] Any -1,-2 negative operator means go from the back.任何-1,-2负运算符表示从后面开始的 go。 When you do [1:-1:-1] , you are telling it to go from lower position and higher position backwards.当您执行[1:-1:-1]时,您是从较低的 position 和较高的 position 向后告诉 go。 That is why it will give you an [] empty list.这就是为什么它会给你一个[]空列表。

What you really want is a[1::-1] telling go from index 1 to end of list backwards - ie 1 then 0你真正想要的是a[1::-1]告诉 go 从索引 1 到列表末尾向后 - 即 1 然后 0

And a[2:] means go from index position 2 to end. a[2:]表示从索引 position 2 到结束的 go。

There fore a[1::-1]+a[2:] will give you [2,1,3,4]因此a[1::-1]+a[2:]会给你[2,1,3,4]

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

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