Skip to main content
 首页 » 编程设计

python之什么时候使用完整列表切片

2025年05月04日13yyy_WW

所以我明白如果我有一个像这样的列表

>>> dinner = ['steak', 'baked potato', 'red wine'] 

那么开头和结尾未指定的切片就是整个列表

>>> dinner[:] 
['steak', 'baked potato', 'red wine'] 

我的问题是这个完整列表切片是否曾在实践中使用过,如果是,它的用例是什么?为什么不引用列表 dinner 而不使用切片符号 [:]?

请您参考如下方法:

完整列表切片是制作列表浅拷贝的常用 Python 语法。

>>> dinner = ['steak', 'baked potato', 'red wine'] 
>>> dinner1 = dinner  # just another reference to the original object 
>>> dinner2 = dinner[:]  # makes a new object 
>>> dinner[0] = 'spam' 
>>> dinner1  # dinner1 reflects the change to dinner 
['spam', 'baked potato', 'red wine'] 
>>> dinner2  # dinner2 doesn't reflect the change to dinner 
['steak', 'baked potato', 'red wine'] 

如果您只是在没有切片的情况下引用原始列表,您还会在新引用中看到对原始列表的更改。这有时是你想要的,有时不是你想要的。