我有这个"模板"词典:
_premium_per_month = {1: [0.0, []], 2: [0.0, []], 2: [0.0, []], 3: [0.0, []], 4: [0.0, []], 5: [0.0, []],
6: [0.0, []], 7: [0.0, []], 8: [0.0, []],
9: [0.0, []], 10: [0.0, []], 11: [0.0, []], 12: [0.0, []]}
有一种方法可以使用这个字典并构建添加值。但是当浅层复制字典中的值发生变化时,它也会在模板字典中发生变化。那么我应该使用深度复制还是有一些提示/技巧来获得更好/更快的复制或模式(可能我的模式是错误的)?
为了更好地理解它的作用,请看一下这个方法(简化为显示核心问题)
def test(_premium_per_month):
#premium_per_month = copy.deepcopy(_premium_per_month) this one works
premium_per_month = _premium_per_month.copy() #not work
for i in range(3):
if i > 0:
premium_per_month[i][0] += 20
return premium_per_month
所以使用简单的副本,当然会改变原始字典。 deepcopy是解决这个问题的正确方法,还是我应该改变别的东西?
答案 0 :(得分:0)
我想如果我把所有模板方法放在一起会更有效率(注意:在这里显示我在评论中提到的那个对象,所以它会显示为什么我使用值作为列表,它被称为{{1}这里根本没有使用contracts_list
)?
_premium_per_month
答案 1 :(得分:0)
创建dict比深度复制更有效:
In [3]: %%timeit
...: _premium_per_month = {1: [0.0, []], 2: [0.0, []], 2: [0.0, []], 3: [0.0, []], 4: [0.0, []], 5: [0.0, []],
...: 6: [0.0, []], 7: [0.0, []], 8: [0.0, []],
...: 9: [0.0, []], 10: [0.0, []], 11: [0.0, []], 12: [0.0, []]}
...:
100000 loops, best of 3: 2.13 µs per loop
In [4]: _premium_per_month = {1: [0.0, []], 2: [0.0, []], 2: [0.0, []], 3: [0.0, []], 4: [0.0, []], 5: [0.0, []],
...: 6: [0.0, []], 7: [0.0, []], 8: [0.0, []],
...: 9: [0.0, []], 10: [0.0, []], 11: [0.0, []], 12: [0.0, []]}
In [5]:
In [5]: from copy import deepcopy
In [6]: timeit d = deepcopy(_premium_per_month)
10000 loops, best of 3: 74.6 µs per loop
因此,不使用模板,使用引用和深度复制在函数中创建dict,以便每次都获得一个新对象:
def test():
premium_per_month = {1: [0.0, []], 2: [0.0, []], 2: [0.0, []], 3: [0.0, []], 4: [0.0, []], 5: [0.0, []],
6: [0.0, []], 7: [0.0, []], 8: [0.0, []],
9: [0.0, []], 10: [0.0, []], 11: [0.0, []], 12: [0.0, []]}