Python列表副本在Python 3.6中不起作用



当我通过现有列表中的副本制作新列表时。我对新列表的更改也反映在旧列表中。我该如何解决。

我已经使用了.popy,但失败了。

# original list
prediction = [{'seriesname': 'Male', 'data': [681, 696, 711, 726, 739]},
  {'seriesname': 'Female', 'data': [101, 104, 107, 109, 112]}]
# make a copy
prediction_percentages = prediction.copy()
# test to check the 2 objects are different
prediction_percentages is prediction
False
# Make a change in new list
prediction_percentages[0]["data"][0] = 1111
# now the changes appear in old list also 
prediction_percentages
[{'seriesname': 'Male', 'data': [1111, 696, 711, 726, 739]},
 {'seriesname': 'Female', 'data': [101, 104, 107, 109, 112]}]
prediction
[{'seriesname': 'Male', 'data': [1111, 696, 711, 726, 739]},
  {'seriesname': 'Female', 'data': [101, 104, 107, 109, 112]}]

最终结果应为

prediction_percentages
[{'seriesname': 'Male', 'data': [1111, 696, 711, 726, 739]},
 {'seriesname': 'Female', 'data': [101, 104, 107, 109, 112]}]
prediction
[{'seriesname': 'Male', 'data': [681, 696, 711, 726, 739]},
  {'seriesname': 'Female', 'data': [101, 104, 107, 109, 112]}]

可以使用复制模块进行列表的深度:

import copy
prediction_percentages = copy.deepcopy(prediction)

您正在制作包含字典(可变对象(列表的浅副本。这意味着两个列表是不同的副本,但它们的元素是相同的。

您可能想要的是 .deepcopy():https://docs.python.org/3/library/copy.html

最新更新