分配list [:] = […]时冒号在Python中做什么?

分配list [:] = […]时冒号在Python中做什么?,第1张

分配list [:] = […]时冒号在Python中做什么?

此语法是切片分配。一片

[:]
意味着整个列表。
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]


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5630558.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存