我遇到了以下代码:
# 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
nums[:] =
nums =
没有做什么?就此而言,nums[:]
nums
没有做什么?
答案 0 :(得分:31)
此语法是切片分配。一片[:]
表示整个列表。 nums[:] =
和nums =
之间的区别在于后者不会替换原始列表中的元素。当有两个对列表的引用时,这是可观察的
>>> a = list(range(10))
>>> b = a
>>> a[:] = [0, 0, 0] # changes what a and b both refer to
>>> b # see below, now you can see the change through b
[0, 0, 0]
要查看区别,只需从上面的序列中移除[:]
。
>>> a = list(range(10))
>>> b = a
>>> a = [0, 0, 0] # a now refers to a different list than b
>>> b # b remains the same
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
要从字面上理解问题的标题,如果list
是变量名而不是内置字,则它将用省略号替换序列的长度
>>> list = [1,2,3,4]
>>> list[:] = [...]
>>> list
[Ellipsis]
答案 1 :(得分:4)
nums = foo
重新绑定名称nums
以引用foo
引用的同一对象。
nums[:] = foo
调用nums
引用的对象的切片赋值,从而使原始对象的内容成为foo
内容的副本。
试试这个:
>>> a = [1,2]
>>> b = [3,4,5]
>>> c = a
>>> c = b
>>> print(a)
[1, 2]
>>> c = a
>>> c[:] = b
>>> print(a)
[3, 4, 5]