python 深拷贝使用


下面代码不是想要的结果:

vals = [{'id':'01','location_id':'a001','number':100},{'id':'02','location_id':'a002','number':200},{'id':'03','location_id':'a003','number':500}]
temp_list = []
temp_vals = {}
new_list = []
for val in vals:
  temp_vals['id'] = val['id']
  temp_vals['number'] = val['number']
  value = [0, False, temp_vals]
  temp_list.append(value)

print temp_list


以下结果不是我们想要的结果:




未使用拷贝解决上面的问题:

# -*- coding: utf-8 -*-

vals = [{'id':'01','location_id':'a001','number':100},{'id':'02','location_id':'a002','number':200},{'id':'03','location_id':'a003','number':500}]
temp_list = []
temp_vals = {}
new_list = []
for val in vals:
  temp_vals['id'] = val['id']
  temp_vals['number'] = val['number']
  value = [0, False, temp_vals]
  temp_list.append(value)
  #把字典置空
  temp_vals = {}

print temp_list

使用拷贝解决上面的问题:

import copy

vals = [{'id':'01','location_id':'a001','number':100},{'id':'02','location_id':'a002','number':200},{'id':'03','location_id':'a003','number':500}]
temp_list = []
temp_vals = {}
new_list = []
for val in vals:
  temp_vals['id'] = val['id']
  temp_vals['number'] = val['number']
  value = [0, False, temp_vals]
  new_list = copy.deepcopy(value)
  temp_list.append(new_list)

print temp_list


想要的结果:



你可能感兴趣的:(python 深拷贝使用)