擅长:python、mysql、java
<p>而公式取决于(C)Python版本和指针大小(有时甚至键的类型!),您可以用<code>sys.getsizeof()</code>来测量它。后面的确切数字适用于64位版本。你知道吗</p>
<p>在Python<strong>2中,它非常简单:280b表示<code>PyDictObject</code>(其容量始终为8)及其<code>PyGC_Head</code>,因此容量是</p>
<pre><code>def cap2(d): return (sys.getsizeof(d)-280)/24 or 8
</code></pre>
<p>这个版本的词典增长了四倍,如果很大的话,增长了一倍。你知道吗</p>
<p>在3.6之前的Python<strong>3</strong>中,有96b的固定开销(除了用于在类实例之间共享属性名的所谓“拆分表”),因此</p>
<pre><code>def cap3(d): return (sys.getsizeof(d)-96)//24
</code></pre>
<p>字典(版本3.5)增长了一倍(在没有删除的情况下)。你知道吗</p>
<p>由于<strong>3.6,开销是112b。进一步的存储更复杂,因为实际的哈希表只存储索引,并且索引的大小是可变的。然后我们必须使用<code>dictobject.c</code>中<code>USABLE_FRACTION</code>的公式,并计算出用于表容量2^<em>n</em>(<em>n</em>=3)的空间是</p>
<pre><code>112+(1<<n)*(n//8+1)+(1<<n+1)//3*24
</code></pre>
<p>这很难精确地反转,但是(考虑到这些严格的假设),你可以近似为2的最大幂,不大于十七分之一(!)尺寸:</p>
<pre><code>def cap36(d):
s=sys.getsizeof(d)//17
n=3
while 1<<n+1<=s: n+=1
return n
</code></pre>
<p>别忘了用容量除以<code>len(d)</code>!你知道吗</p>