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


想要的結果:



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章