切片插入问题,L[1:1]
练习一些Python,这是一种很容易掌握的语言。
我
>>> L = [1,2,3,4]
>>> L[1:1] = [1,2,3]
>>> L
[1, 1, 2, 3, 2, 3, 4]
在第二行实际上 L[1:1]
是空列表,但是 python 如何理解插入 [1,2,3]
列表从<代码>1。我猜有一些内部结构对我们来说不透明,显然,我猜 L[1:1]
返回对索引 1
的引用,即使它返回一个空列出...
最美好的祝愿, 乌穆特
practising some python, which is a pretty easy language to grab up.
I have
>>> L = [1,2,3,4]
>>> L[1:1] = [1,2,3]
>>> L
[1, 1, 2, 3, 2, 3, 4]
so on line two actually L[1:1]
is empty list, but how can python understand that insert the [1,2,3]
list to starting from 1
. I guess there is some internals which is not transparent to us, here apparently, I guess L[1:1]
returns a reference to index 1
even if that returns an empty list...
Best wishes,
Umut
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
L[1:1]
表示列表L
的切片,从索引 1(第二个元素)开始,一直到但不包括索引 1。因此它是一个空列表。在作业的右侧,它只是一个匿名空列表。但在左侧,赋值知道切片是在哪里进行的,并且可以将新的列表值拼接到正确的位置。L[1:1]
means the slice of the listL
starting at index 1 (the second element), up to but not including index 1. So it is an empty list. On the right-hand side of an assignment, it is simply an anonymous empty list. But on the left-hand side, the assignment knows where the slice has been made, and can splice in the new list value into the proper place.切片的行为有所不同,具体取决于它是在表达式的左侧还是右侧。当它位于左侧时,它不会返回列表 - 相反,它表现为切片对象,它了解有关切片的更多信息,并且专门重写了赋值以作为插入进行操作。
Slicing behaves differently depending on whether it's on the left- or right-hand side of an expression. When it's on the left side, it doesn't return a list - instead, it behaves as a slice object, which knows more about slices and has assignment specifically overridden to operate as insertion.
在我看来,官方的 Python 教程对此解释得最好。 第 3.1.2 章 的末尾有以下图表:
这说明了什么是你可以将索引视为指向元素之间。因此,在此图中,如果指定切片
[1:1]
,则实际上指的是H
和e
之间的空格,但不是包括他们。如果您想覆盖
H
和e
,您可以指定切片[0:2]
。The official Python Tutorial explains it best, in my opinion. The end of Chapter 3.1.2 has the following diagram:
What this illustrates is that you can think of the indices as pointing BETWEEN the elements. So in this illustration, if specifying a slice
[1:1]
, you are actually referring to the space betweenH
ande
, but not including them.If you wanted to overwrite
H
ande
, you would specify the slice[0:2]
.