[英]Lists simple slicing in Python?
I understand slicing but i don't get why this one prints 3 ??? 我知道切片,但我不知道为什么这个打印3张?
so here is my understanding: 所以这是我的理解:
it says x = [0,1,2,3,4] then 它说x = [0,1,2,3,4]然后
index 2 to 2 will be replaced by [0,1,2,3,4] 索引2到2将替换为[0,1,2,3,4]
so x[5] is not in range 所以x [5]不在范围内
x = range(5)
x[2:3] = range(5)
print x[5]
I think you'll undestand what's going on if you print the whole x
list after doing the slice assignment. 我认为如果在执行切片分配后打印整个x
列表,您将无法理解所发生的情况。 It will be [0, 1, 0, 1, 2, 3, 4, 3, 4]
. 它将是[0, 1, 0, 1, 2, 3, 4, 3, 4]
。 The 2
from the initial range has been replaced by the whole second range, expanding the list so it will fit. 初始范围内的2
已被整个第二范围所取代,从而扩展了列表以使其适合。
You can only expand a list with a slice assignment of this kind if the slice has a step of 1
or -1
. 如果切片的步长为1
或-1
则只能使用这种切片分配来展开列表。 If you assign to a list with a larger step size, the sequence you're replacing it with has to be exactly the same size. 如果您将列表分配给较大的步长,则替换它的顺序必须完全相同。
After this change... 更改之后...
x[2:3] = range(5)
x prints...[0, 1, 0, 1, 2, 3 , 4, 3, 4], such that the x[5] is 3 now. X打印... [0,1,0,1,2,3,4,3,4],使得x [5]为3现在。
Spilt this in parts what you are doing : 将此内容部分地撒在您的工作中:
x = range(5)
print x
[0, 1, 2, 3, 4]
x[2:3] = range(5)
Here what you are doing, you want value of index x[2:3] to be range(5), Now if you print x[2:3],it will return you [2] in the list 在这里,您要使索引x [2:3]的值成为range(5),现在,如果您打印x [2:3],它将返回列表中的[2]
Print x[2:3]
[2]
so now when you initialize x[2:3] = range(5) it will insert range(5) which is [0,1,2,3,4] in index x[2:3] that means will replace value of item 2. 因此,现在当您初始化x [2:3] = range(5)时,它将在索引x [2:3]中插入[0,1,2,3,4]的range(5),这将替换项目2。
After this if you print x 在此之后,如果您打印x
x[2:3] = range(5)
print x
[0, 1, 0, 1, 2, 3, 4, 3, 4]
Now if you print x[5] it will return 3 as on 5 index value is 3. 现在,如果您打印x [5],它将返回3,因为5的索引值为3。
x[0] = 0
x[1] = 1
x[2] = 0
x[3] = 1
x[4] = 2
x[5] = 3
x[6] = 4
x[7] = 3
x[8] = 4
hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.