下面代碼不是想要的結果:
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
想要的結果: