问题描述
我偶尔会看到像这样的Python代码中使用的列表切片语法:
I occasionally see the list slice syntax used in Python code like this:
newList = oldList[:]
当然,这与以下内容相同:
Surely this is just the same as:
newList = oldList
或者我想念什么吗?
推荐答案
就像NXC所说,Python变量名称实际上指向一个对象,而不是内存中的特定位置.
Like NXC said, Python variable names actually point to an object, and not a specific spot in memory.
newList = oldList
将创建两个指向同一对象的不同变量,因此,更改oldList
也会更改newList
.
newList = oldList
would create two different variables that point to the same object, therefore, changing oldList
would also change newList
.
但是,当您执行newList = oldList[:]
时,它将切片"列表,并创建一个新列表. [:]
的默认值为0,并且位于列表的末尾,因此它将复制所有内容.因此,它使用第一个中包含的所有数据创建了一个新列表,但是可以更改两个列表而无需更改另一个.
However, when you do newList = oldList[:]
, it "slices" the list, and creates a new list. The default values for [:]
are 0 and the end of the list, so it copies everything. Therefore, it creates a new list with all the data contained in the first one, but both can be altered without changing the other.
这篇关于没有明显原因使用的Python列表切片语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!