在py中,对象的赋值并不会copy 对象,而是增加对象的引用,如果确实需要copy,引用copy.copy/copt.deepcopy
例子:
lis=['a','b','c']
list1=[{'a':'1'},{'a':'2'},{'a':'3'}]
for i in list1:
i['a']=i['a']+'_5'
print i
print list1
import copy
list2=[{'a':'1'},{'a':'2'},{'a':'3'}]
for i in list2:
j=copy.copy(i)
j['a']=j['a']+'_5'
print j
print list2
执行结果
{'a': '1_5'}
{'a': '2_5'}
{'a': '3_5'}
[{'a': '1_5'}, {'a': '2_5'}, {'a': '3_5'}]
{'a': '1_5'}
{'a': '2_5'}
{'a': '3_5'}
[{'a': '1'}, {'a': '2'}, {'a': '3'}]
网友评论