对于list [:] = [...]赋值的冒号在Python中做什么

sin*_*inθ 14 python python-3.x

我来自以下代码:

# 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
Run Code Online (Sandbox Code Playgroud)

nums[:] =nums =不是做什么的?就此而言,那不做nums[:]什么nums

Rya*_*ing 35

此语法是切片分配.一片[:]意味着整个列表.nums[:] =和之间的区别在于nums =后者不会替换原始列表中的元素.当有两个对列表的引用时,这是可观察的

>>> original = [1, 2, 3]
>>> other = original
>>> original[:] = [0, 0] # changes what both original and other refer to 
>>> other # see below, now you can see the change through other
[0, 0]
Run Code Online (Sandbox Code Playgroud)

要查看差异,只需[:]从上面的序列中删除.

>>> 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]
Run Code Online (Sandbox Code Playgroud)

要从字面上取问题的标题,如果list是变量名而不是内置,它将用省略号替换序列的长度

>>> list = [1,2,3,4]
>>> list[:] = [...]
>>> list
[Ellipsis]
Run Code Online (Sandbox Code Playgroud)

  • @Brady Huang 没有准确描述这一点 (2认同)
  • @vincentthorpe `lst[:]` 后面没有 `=` 调用 `__getitem__`,而 `lst[:] = ` 调用 `__setitem__`,所以 `[]` 和 `[]=` 最好被认为是两个不同的运营商 (2认同)

小智 5

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]
Run Code Online (Sandbox Code Playgroud)