python list浅拷贝_Python List的浅拷贝

有两种方法做Python List的浅拷贝(Shallow Copy),使用切片操作符([:])或者list创建函数,等号(=)没有做copy,并没有创建一个新的List。如下代码:

>>> list1 = [1,2,3,4]

>>> list2 = list1 # no new list created.

>>> list2

[1, 2, 3, 4]

>>> list2[0] = 5

>>> list2

[5, 2, 3, 4]

>>> list1

[5, 2, 3, 4]

>>>

>>> list3 = list1[:] # shallow copy, list3 is a new list. Equivalent to list3 = list1.copy()

>>> list3[0] = 6

>>> list3

[6, 2, 3, 4]

>>> list1

[5, 2, 3, 4]

>>>

>>> id(list1)

41114480

>>> id(list2)

41114480

>>> id(list3)

41114400

>>>

>>> list4 = list(list1) # also shallow copy.

>>> list4

[5, 2, 3, 4]

>>> id(list4)

43406200

>>> list4[0] = 7

>>> list4

[7, 2, 3, 4]

>>> list1

[5, 2, 3, 4]

>>>

浅拷贝和深拷贝各有用处,并没有谁好谁坏。深拷贝是完全重新创建了一个包含全局层次数据的新的List,这样在后续操作上可以隔离,大部分时候,浅拷贝很好用,一份数据在各个函数内都可以引用。如何坐深拷贝,请参考:Python的深拷贝和浅拷贝

使用加号(+)将两个list连接起来,也是创造一个新的list,也是浅拷贝:

>>> list6 = [1, [2,3]]

>>> list7 = [4, [5,6]]

>>> list8 = list6 + list7 # shallow copy to create a new list by concatenate two other lists.

>>> list8

[1, [2, 3], 4, [5, 6]]

>>> list8[1][0] = 9

>>> list6

[1, [9, 3]]

>>> list8[3][0] = 9

>>> list7

[4, [9, 6]]

>>>

>>> id(list6)

41114360

>>> id(list7)

41113720

>>> id(list8)

41114240

>>>

使用加号的方式做浅拷贝相对隐蔽,要注意。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值