所以我了解如果我有一个类似

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


如果仅参考原始列表而不包含切片,则还将在新参考中看到对原始列表的更改。有时这就是您想要的,有时不是您想要的。

10-08 13:56