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

时间:2015-09-08 02:36:28

标签: 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

nums[:] = nums =没有做什么?就此而言,nums[:] nums没有做什么?

2 个答案:

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