python复制--笔记
对象引用:
>>> songs = ["Bee","Core","Love"] >>> bat = songs >>> songs, bat (['Bee', 'Core', 'Love'], ['Bee', 'Core', 'Love']) 对复制列表进行改变 >>> bat[2] = "Here" >>> songs,bat (['Bee', 'Core', 'Here'], ['Bee', 'Core', 'Here'])
当我们需要单独副本时,则需要的不再仅仅是一个对象引用
>>> songs = ["Bee","Core","Love"] >>> bat = songs[:] >>> bat[2] = "Here" >>> songs,bat (['Bee', 'Core', 'Love'], ['Bee', 'Core', 'Here'])
对字典与集合,这种复制操作使用dict.copy()与set.copy()来实现。
复制的另一种方法:类型名作为函数,待复制的组合数据类型作为参数
>>> copy_of_dict_d = dict(d) >>> copy_of_list_L = list(L) >>> copy_of_set_s = set(s)
上述的复制都是浅拷贝,如果要实现深拷贝,使用copy模块
>>> x=[53,48,["A","B","C"]] >>> y=x[:] >>> x,y ([53, 48, ['A', 'B', 'C']], [53, 48, ['A', 'B', 'C']]) >>> y[1]=20 >>> x[2][0]="F" >>> x,y ([53, 48, ['F', 'B', 'C']], [53, 20, ['F', 'B', 'C']])
深拷贝,使用copy.deepcopy方法
>>> import copy >>> x=[53,48,["A","B","C"]] >>> y = copy.deepcopy(x) >>> y[1]=20 >>> x[2][0]="F" >>> x,y ([53, 48, ['F', 'B', 'C']], [53, 20, ['A', 'B', 'C']])