此语法是切片分配。一片[:]
意味着整个列表。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]