【问题标题】:What does colon at assignment for list[:] = [...] do in Python [duplicate]list[:] = [...] 赋值时的冒号在 Python 中做了什么 [重复]
【发布时间】:2015-12-03 14:01:59
【问题描述】:

我遇到了以下代码:

# 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 不做的事情?

【问题讨论】:

  • 问和回答我相信。 What does [:] in Python mean
  • @CollinD 没看到这个问题,谢谢。但仍然没有回答作业问题
  • 我投票决定重新打开,因为我认为链接的副本没有解释切片分配。我一定是打开了错误的链接,因为它确实解释了切片分配。

标签: python python-3.x


【解决方案1】:

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]

【讨论】:

  • 我认为更好的答案
  • "...重新绑定..."确实,+1
【解决方案2】:

此语法是切片赋值。 [:] 的一部分表示整个列表。 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]

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

>>> list = [1,2,3,4]
>>> list[:] = [...]
>>> list
[Ellipsis]

【讨论】:

  • 简单地说,(list[:] = ...) 是值类型,但 (list = ...) 是引用类型
  • @Brady Huang 描述不准确
  • 您是说切片符号list[:] 表示引用,而list 表示副本?那么为什么在for in list: 中如果你传递list 本身并在循环中插入一些元素,这个循环将永远不会结束,因为它会增加它的长度,它将永远存在。这意味着如果你通过 list 没有 [:] 你正在传递参考。很矛盾啊
  • [:] 运算符,如果你把 Lvalue 或 Rvalue 放在它意味着不同
  • @vincentthorpe lst[:] 后面没有= 调用__getitem__,而lst[:] = 调用__setitem__,所以[][]= 最好被认为是两个不同的运算符
猜你喜欢
  • 2012-11-28
  • 2013-11-19
  • 2012-12-20
  • 2020-03-19
  • 2016-04-10
  • 2016-03-28
  • 2014-11-24
  • 2013-09-15
  • 2021-08-12
相关资源
最近更新 更多