当通过调用列表(a)制作列表副本时,Python是否会预先分配列表的确切大小?
我的理解是,在将数百个项目附加到列表中时,最终Python将创建一个带有更大缓冲区的全新列表,以便可以继续添加其他元素。
但是,假设我有以下清单:
a = [1, 2, 3, 4, 5]
b = list(a)
既然Python从技术上知道B将拥有多少要素,那么它将采用“智能”方法并提前分配5个空间?
因此,与使用for a循环相比,上述方法在创建深层副本方面会更有效吗?例如:
b = []
for i in a:
b.append(i)
It is my understanding that when appending hundreds of items to a list, eventually Python will create a brand new list with a larger buffer so that additional elements can continue to be added.
However, let's say I have a list as follows:
a = [1, 2, 3, 4, 5]
b = list(a)
Since Python technically knows how many elements b will hold, will it take the "smart" approach and allocate 5 spaces in advance?
Accordingly, would the above approach be more efficient in creating a deep copy compared to using a for loop? For example:
b = []
for i in a:
b.append(i)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论