您的位置:首页 > 编程语言 > Python开发

python 深拷贝使用

2014-04-09 17:45 357 查看
下面代码不是想要的结果:

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


想要的结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: