在 Python 中为 list[:] = [...] 赋值的冒号有什么作用 [英] What does colon at assignment for list[:] = [...] do in Python
问题描述
我遇到了以下代码:
# O(n) 空间def旋转(自我,数字,k):deque = collections.deque(nums)k %= len(nums)对于 xrange(k) 中的 _:deque.appendleft(deque.pop())nums[:] = list(deque) # <- 有问题的代码
nums[:] =
做了哪些 nums =
没有做的事情?就此而言,nums[:]
做了什么而 nums
没有做?
此语法是切片赋值.一片 [:]
表示整个列表.nums[:] =
和 nums =
之间的区别在于后者不替换原始列表中的元素.当有两个对列表的引用时,这是可以观察到的
要查看差异,只需从上面的赋值中删除 [:]
.
<小时>
从字面上看问题的标题,如果 list
是变量名而不是内置变量,它将用省略号替换序列的长度
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?
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
>>> 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 = [1,2,3,4]
>>> list[:] = [...]
>>> list
[Ellipsis]
这篇关于在 Python 中为 list[:] = [...] 赋值的冒号有什么作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!