您的位置:首页 > 编程语言 > Python开发

python list 的复制拷贝的简单介绍

2012-10-13 13:10 519 查看
list ”=“的效果

在python中,又时需要复制一个list,但是用"="是达不到复制的效果的。

比如:

l1=['hello','world']
l2=l1

这时候,只不过又添加了一个指向list的”指针“l2.换句话说,是给同一件商品贴上了两个标签。如下图:



可以做一下测试:

>>> l1=["hello","world"]
>>> l2=l1
>>> l1[0]="world"
>>> print l1
['world', 'world']
>>> print l2
['world', 'world']

如果要对list进行复制,建议采用切片的方法:

l2=l1[:],例如:

>>> l1=["hello","world"]
>>> l2=l1[:]
>>> print l1
['hello', 'world']
>>> print l2
['hello', 'world']
>>> l1[0]="world"
>>> print l1
['world', 'world']
>>> print l2
['hello', 'world']
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  list python 测试