您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

分配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]
python 2022/1/1 18:33:25 有215人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶