在 Python 中为 list[:] = [...] 赋值的冒号有什么作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32448414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does colon at assignment for list[:] = [...] do in Python
提问by sinθ
I came accross the following code:
我遇到了以下代码:
# O(n) space
def rotate(self, nums, k):
deque = collections.deque(nums)
k %= len(nums)
for _ in xrange(k):
deque.appendleft(deque.pop())
nums[:] = list(deque) # <- Code in question
What does nums[:] =
do that nums =
does not? For that matter, what does nums[:]
do that nums
does not?
什么nums[:] =
不做nums =
?就此而言,什么nums[:]
不做nums
呢?
采纳答案by Ryan Haining
This syntax is a slice assignment. A slice of [:]
means the entire list. The difference between nums[:] =
and nums =
is that the latter doesn't replace elements in the original list. This is observable when there are two references to the list
此语法是切片分配。切片[:]
意味着整个列表。nums[:] =
和之间的区别在于nums =
后者不会替换原始列表中的元素。当有两个对列表的引用时,这是可观察到的
>>> original = [1, 2, 3]
>>> other = original
>>> original[:] = [0, 0] # changes the contents of the list that both
# original and other refer to
>>> other # see below, now you can see the change through other
[0, 0]
To see the difference just remove the [:]
from the assignment above.
要查看差异,只需[:]
从上面的分配中删除。
>>> original = [1, 2, 3]
>>> other = original
>>> original = [0, 0] # original now refers to a different list than other
>>> other # other remains the same
[1, 2, 3]
To take the title of your question literally, if list
is a variable name and not the builtin, it will replace the length of the sequence with an ellipsis
从字面上看问题的标题,如果list
是变量名而不是内置变量,它将用省略号替换序列的长度
>>> list = [1,2,3,4]
>>> list[:] = [...]
>>> list
[Ellipsis]
回答by sinθ
nums = foo
rebinds the name nums
to refer to the same object that foo
refers to.
nums = foo
重新绑定名称nums
以引用所引用的同一对象foo
。
nums[:] = foo
invokes slice assignment on the object that nums
refers to, thus making the contents of the original object a copy of the contents of foo
.
nums[:] = foo
对引用的对象调用切片赋值nums
,从而使原始对象的内容成为 的内容的副本foo
。
Try this:
尝试这个:
>>> a = [1,2]
>>> b = [3,4,5]
>>> c = a
>>> c = b
>>> print(a)
[1, 2]
>>> c = a
>>> c[:] = b
>>> print(a)
[3, 4, 5]