[英]Slice notation in python - need clarification on a code snippet
I'm new to python, and while reading about slice notation, I came across the following code snippet. 我是python的新手,在阅读切片表示法时,我遇到了以下代码片段。 I was able to understand and use it in very simple examples, but I wasn't able to grasp its usage in the following example.
我能够在非常简单的示例中理解和使用它,但我无法在以下示例中掌握它的用法。 Any explanation will really help!
任何解释都会有所帮助!
>>> a = [1,2]
>>> a[1:1] = [3,4,5]
>>> print a
[1, 3, 4, 5, 2]
>>> a = [1,2]
>>> a[0:1] = [3,4,5]
>>> print a
[3, 4, 5, 2]
a[n:m] = b
# is essentially* equivalent to
a = a[:n] + b + a[m:]
and you could read this as "replace a[n:m]
with b
" (since a = a[:n] + a[n:m] + a[m:]
). 你可以把它读成“用
b
替换a[n:m]
”(因为a = a[:n] + a[n:m] + a[m:]
)。
*actually slicing mutates the list in-place (that is, id(a)
remains unchanged) which will usually be preferable (wheras setting a=
creates our new a
at a different memory location). *实际上切片使列表就地变异(即,
id(a)
保持不变),这通常是更可取的(当设置a=
在不同的内存位置创建新的a
时)。
So in your examples: 所以在你的例子中:
a = [1,2]
#a[1:1] = [3,4,5]
a = a[:1] + [3,4,5] + a[1:]
# [1] [2]
[1, 3, 4, 5, 2]
a = [1,2]
#a[0:1] = [3,4,5]
a = a[:0] + [3,4,5] + a[1:]
# [] [2]
[3, 4, 5, 2]
a[1:1]
is an empty slice at the position between the first and second elements in the list. a[1:1]
是列表中第一个和第二个元素之间位置的空切片。
So a[1:1] = [3,4,5]
means "insert the elements 3,4,5
after the first element of the list". 所以
a[1:1] = [3,4,5]
意味着“在列表的第一个元素之后插入元素3,4,5
”。
a[0:1]
is the slice from the first element up to (but excluding) the second element in the list. a[0:1]
是从第一个元素到列表中第二个元素(但不包括)的切片。
So a[0:1] = [3,4,5]
means "replace the first element of the list with the elements 3,4,5
". 所以
a[0:1] = [3,4,5]
意味着“用元素3,4,5
替换列表的第一个元素”。
Perhaps this visualization helps: 也许这种可视化有助于
| h | e | l | l | o | <-- string "hello"
0 1 2 3 4 5 <-- slice positions
^---^ <-- slice [0:1]: "h"
^ <-- slice [1:1]: ""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.