切片插入问题,L[1:1]

发布于 2024-10-10 13:12:14 字数 367 浏览 2 评论 0原文

练习一些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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

水染的天色ゝ 2024-10-17 13:12:14

L[1:1] 表示列表 L 的切片,从索引 1(第二个元素)开始,一直到但不包括索引 1。因此它是一个空列表。在作业的右侧,它只是一个匿名空列表。但在左侧,赋值知道切片是在哪里进行的,并且可以将新的列表值拼接到正确的位置。

L[1:1] means the slice of the list L 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.

毁我热情 2024-10-17 13:12:14

切片的行为有所不同,具体取决于它是在表达式的左侧还是右侧。当它位于左侧时,它不会返回列表 - 相反,它表现为切片对象,它了解有关切片的更多信息,并且专门重写了赋值以作为插入进行操作。

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.

江南烟雨〆相思醉 2024-10-17 13:12:14

在我看来,官方的 Python 教程对此解释得最好。 第 3.1.2 章 的末尾有以下图表:

 +---+---+---+---+---+
 | H | e | l | p | A |
 +---+---+---+---+---+
 0   1   2   3   4   5

这说明了什么是你可以将索引视为指向元素之间。因此,在此图中,如果指定切片 [1:1],则实际上指的是 He 之间的空格,但不是包括他们。

如果您想覆盖 He,您可以指定切片 [0:2]

The official Python Tutorial explains it best, in my opinion. The end of Chapter 3.1.2 has the following diagram:

 +---+---+---+---+---+
 | H | e | l | p | A |
 +---+---+---+---+---+
 0   1   2   3   4   5

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 between H and e, but not including them.

If you wanted to overwrite H and e, you would specify the slice [0:2].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文