擅长:python、mysql、java
<p><strong>更新:</strong>
如果您想更改dict中的列表,您无法避免<strong>deepcopy()</strong>,但您应该执行以下操作:</p>
<p>“保存”只保存图的<strong>可变/可删除元素</strong>(即列表)的值,<strong>不</strong>完整图</strong>。然后对dict/graph进行所需的修改,然后可以使用“saved”元素进一步修改graph。在</p>
<p>使用<code>dict.copy()</code>,如下所示,d.copy()的速度快了100000倍:</p>
<pre><code>from copy import deepcopy
from time import time
# with simply assignment -
d = {"a":[x for x in range(1000000)]}
t = time()
e = d
print 'elapsed time with standard assignment:', time()-t
e["b"] = [1,2,3]
del e["a"]
print d.keys()
# with deepcopy()
d = {"a":[x for x in range(1000000)]}
t = time()
e = deepcopy(d)
print '\nelapsed time with deepcopy():', time()-t
e["b"] = [1,2,3]
del e["a"]
print d.keys()
# with d.copy() -
d = {"a":[x for x in range(1000000)]}
t = time()
e = d.copy()
print '\nelapsed time with d.copy():', time()-t
e["b"] = [1,2,3]
del e["a"]
print d.keys()
</code></pre>
<p><strong>输出:</strong></p>
^{pr2}$