What does colon at assignment for list[:] = [...] do in Pyth



我遇到了以下代码:

# 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没有做的事情呢?

这个语法是切片赋值。[:]的切片意味着整个列表。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]

要查看差异,只需从上面的赋值中删除[:]

>>> 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]

注:文森特·索普下面的评论要么是不正确的,要么是与问题无关的。这不是值与引用语义的问题,也不是将操作符应用于左值还是右值的问题。

nums = foo将名称nums重新绑定为foo所引用的同一对象。

nums[:] = foonums所引用的对象调用切片赋值,从而使原始对象的内容成为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]

最新更新