1.python 中的拷贝:Copy and deepCopy
时间:2010-07-16 来源:dragonlin06
浅度拷贝和深度拷贝
第一个是象序列的分片操作[:] 或着是字典的copy方法.
第二个是深度嵌套结构的象类和实例的deepcopy
>>> import copy
>>> listOne=[1,2,3,3]
>>> li = listOne
>>> li
[1, 2, 3, 3]
>>> listOne.append(32)
>>> li
[1, 2, 3, 3, 32]
>>> li=listOne[:]
>>> li
[1, 2, 3, 3, 32]
>>> listOne.append(123)
>>> li
[1, 2, 3, 3, 32]
>>> listOne
[1, 2, 3, 3, 32, 123]
>>> listOne=[{"name":"Willie","city":"Providence,RI"},1,"tomato",3.0]
>>> listTwo = listOne[:]
>>> listTwo
[{'city': 'Providence,RI', 'name': 'Willie'}, 1, 'tomato', 3.0]
>>> listThree = copy.deepcopy(listOne)
>>> listThree
[{'city': 'Providence,RI', 'name': 'Willie'}, 1, 'tomato', 3.0]
>>> listOne.append('kid')
>>> listOne[0]["city"]='San Francisco,CA'
>>> print listOne,listTwo,listThree
[{'city': 'San Francisco,CA', 'name': 'Willie'}, 1, 'tomato', 3.0, 'kid'] [{'city': 'San Francisco,CA', 'name': 'Willie'}, 1, 'tomato', 3.0] [{'city': 'Providence,RI', 'name': 'Willie'}, 1, 'tomato', 3.0]
第一个是象序列的分片操作[:] 或着是字典的copy方法.
第二个是深度嵌套结构的象类和实例的deepcopy
>>> import copy
>>> listOne=[1,2,3,3]
>>> li = listOne
>>> li
[1, 2, 3, 3]
>>> listOne.append(32)
>>> li
[1, 2, 3, 3, 32]
>>> li=listOne[:]
>>> li
[1, 2, 3, 3, 32]
>>> listOne.append(123)
>>> li
[1, 2, 3, 3, 32]
>>> listOne
[1, 2, 3, 3, 32, 123]
>>> listOne=[{"name":"Willie","city":"Providence,RI"},1,"tomato",3.0]
>>> listTwo = listOne[:]
>>> listTwo
[{'city': 'Providence,RI', 'name': 'Willie'}, 1, 'tomato', 3.0]
>>> listThree = copy.deepcopy(listOne)
>>> listThree
[{'city': 'Providence,RI', 'name': 'Willie'}, 1, 'tomato', 3.0]
>>> listOne.append('kid')
>>> listOne[0]["city"]='San Francisco,CA'
>>> print listOne,listTwo,listThree
[{'city': 'San Francisco,CA', 'name': 'Willie'}, 1, 'tomato', 3.0, 'kid'] [{'city': 'San Francisco,CA', 'name': 'Willie'}, 1, 'tomato', 3.0] [{'city': 'Providence,RI', 'name': 'Willie'}, 1, 'tomato', 3.0]
相关阅读 更多 +