为什么从列表创建列表会使它更大? [英] Why does creating a list from a list make it larger?

查看:61
本文介绍了为什么从列表创建列表会使它更大?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在应该是相同列表的地方使用sys.getsizeof时,我看到了一些不一致之处. (Python 2.7.5)

I'm seeing some inconsistencies when using sys.getsizeof on what should be identical lists. (Python 2.7.5)

>>> lst = [0,1,2,3,4,5,6,7,8,9]
>>> sys.getsizeof(lst)
76
>>> lst2 = list(lst)
>>> sys.getsizeof(lst2)
104
>>> lst3 = list(lst2)
>>> sys.getsizeof(lst3)
104
>>> sys.getsizeof(lst[:])
76
>>> sys.getsizeof(lst2[:])
76

有人有一个简单的解释吗?

Does anybody have a simple explanation?

推荐答案

使用列表文字,VM会创建具有设置长度的列表.当将序列传递给list()构造函数时,元素将被一个接一个地添加(通过调整大小操作进行了汇总以分摊成本,最终列表通常会比源列表大.

With a list literal, the VM creates the list with a set length. When passing a sequence to the list() constructor the elements are added one by one (via list.extend()) and as such the list is resized when appropriate. Since the resize operation overallocates in order to amortize the cost, the final list will usually be larger than the source list.

这篇关于为什么从列表创建列表会使它更大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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