深入理解python中列表的深浅复制

【1】在前面学习列表的知识中,列表的复制有个copy()方法

aList = ["a","b","c","d"]
#将aList复制给bList
bList = aList.copy()
print(aList)
#['a', 'b', 'c', 'd']
print(bList)
#['a', 'b', 'c', 'd']

  假如将列表aList中的"b"元素改成"B",bList的元素是否会改变?

aList = ["a","b","c","d"]
#将aList复制给bList
bList = aList.copy()
#修改aList中的元素"b"
aList[1] = "B"
print(aList)
#['a', 'B', 'c', 'd']
print(bList)
#['a', 'b', 'c', 'd']

  结果发现修改了列表aList的元素"b",列表bList却没有发生变化。

  下面用一个图来分析它的原理

  分析:aList指向一个列表,把aList复制了一份给bList,由于修改的是aList,所以bList不会被修改

【2】列表嵌套的复制

aList = ["a",["e","f","g"],"c","d"]
#将aList复制给bList
bList = aList.copy()
#把aList中的"e"改为"E"
aList[1][1]= "E"
print(aList)
#['a', ['e', 'E', 'g'], 'c', 'd']
print(bList)
#['a', ['e', 'E', 'g'], 'c', 'd']

  列表嵌套的复制,发现aList和bList的都被修改了。原理如下

  分析:嵌套的列表单独分配一块空间,从第一层列表中去引用地址,复制的bList 也是引用的地址,所以真实的值一变,两个列表的内部列表的值也就变了。

  则:copy()方法只能复制一层,这也叫做浅复制。

  注意:第二个列表copy 第一个列表,实际上第二个列表的每个元素是第一个列表每个元素的引用

 【3】浅复制的三种方法

  1、使用copy模块

import copy
aList = ["a","b","c"]
bList = copy.copy(aList)
print(aList)
#['a', 'b', 'c']
print(bList)
#['a', 'b', 'c']
aList = ["a",["e","f","g"],"c","d"]
bList = copy.copy(aList)
#把aList中的"e"改为"E"
aList[1][1]= "E"
print(aList)
#['a', ['e', 'E', 'g'], 'c', 'd']
print(bList)
#['a', ['e', 'E', 'g'], 'c', 'd']

  2、使用列表的切片方法

aList = ["a",["e","f","g"],"c","d"]
bList = aList[:]
print(aList)
#['a', ['e', 'f', 'g'], 'c', 'd']
print(bList)
#['a', ['e', 'f', 'g'], 'c', 'd']

  3、使用list()方法

aList = ["a",["e","f","g"],"c","d"]
bList = list(aList)
print(aList)
#['a', ['e', 'f', 'g'], 'c', 'd']
print(bList)
#['a', ['e', 'f', 'g'], 'c', 'd']
aList[1][1]= "E"
print(aList)
#['a', ['e', 'E', 'g'], 'c', 'd']
print(bList)
#['a', ['e', 'E', 'g'], 'c', 'd']

【4】深复制

import copy
aList = ["a",["e","f","g"],"c","d"]
#深复制
bList = copy.deepcopy(aList)
print(aList)
#['a', ['e', 'f', 'g'], 'c', 'd']
print(bList)
#['a', ['e', 'f', 'g'], 'c', 'd']
aList[1][1]= "E"
print(aList)
#['a', ['e', 'E', 'g'], 'c', 'd']
print(bList)
#['a', ['e', 'f', 'g'], 'c', 'd']

 

posted @ 2018-03-01 00:27  今晚打老虎i2016  阅读(352)  评论(0编辑  收藏  举报