在 Python 中为 list[:] = [...] 赋值的冒号有什么作用 [英] What does colon at assignment for list[:] = [...] do in Python

查看:45
本文介绍了在 Python 中为 list[:] = [...] 赋值的冒号有什么作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下代码:

# O(n) 空间def旋转(自我,数字,k):deque = collections.deque(nums)k %= len(nums)对于 xrange(k) 中的 _:deque.appendleft(deque.pop())nums[:] = list(deque) # <- 有问题的代码

nums[:] = 做了哪些 nums = 没有做的事情?就此而言,nums[:] 做了什么而 nums 没有做?

解决方案

此语法是切片赋值.一片 [:] 表示整个列表.nums[:] =nums = 之间的区别在于后者不替换原始列表中的元素.当有两个对列表的引用时,这是可以观察到的

<预><代码>>>>原始 = [1, 2, 3]>>>其他 = 原创>>>original[:] = [0, 0] # 改变列表的内容#原文和其他参考>>>其他 # 见下文,现在你可以通过其他看到变化[0, 0]

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

<预><代码>>>>原始 = [1, 2, 3]>>>其他 = 原创>>>original = [0, 0] # original 现在引用的列表与其他列表不同>>>other # 其他保持不变[1, 2, 3]

<小时>

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

<预><代码>>>>列表 = [1,2,3,4]>>>列表[:] = [...]>>>列表[省略]

I came accross the following code:

# 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

What does nums[:] = do that nums = does not? For that matter, what does nums[:] do that nums does not?

解决方案

This syntax is a slice assignment. A slice of [:] means the entire list. The difference between nums[:] = and nums = is that the latter doesn't replace elements in the original list. This is observable when there are two references to the list

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

To see the difference just remove the [:] from the assignment above.

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


To take the title of your question literally, if list is a variable name and not the builtin, it will replace the length of the sequence with an ellipsis

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

这篇关于在 Python 中为 list[:] = [...] 赋值的冒号有什么作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆