没有明显原因使用的Python列表切片语法 [英] Python list slice syntax used for no obvious reason

查看:148
本文介绍了没有明显原因使用的Python列表切片语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶尔会看到像这样的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列表切片语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆