Python复制包含引用副本和值副本的列表

时间:2014-08-05 10:33:13

标签: python

我试图创建两个列表a和b。

和a和b应满足这些条件:

len(a) == len(b) == 5
a == b
a is not b
a[0] is b[0]
a[1] is not b[1]
a[2] is b[2]
a[3] is not b[3]
a[4] is b[4]

我尝试使用

b = copy.deepcopy(a)

但它没有通过

a[1] is not b[1]
and
a[3] is not b[3]

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

以下是一种可行的方法:

a = [0, [1], 2, [3], 4]

b = copy.deepcopy(a)

这可行,因为deepcopy会插入:

  • 对于不可变对象(如intstr),对同一对象的引用,(共享相等 和< / strong> 身份);或
  • 对于可变对象(如list),对对象(深层)副本的引用(共享相等 但不是 身份);

进入新对象。

演示:

>>> from copy import deepcopy
>>> a = [0, [1], 2, [3], 4]
>>> b = deepcopy(a)
>>> print a == b, a is b
True False
>>> for a_i, b_i in zip(a, b):
    print a_i == b_i, a_i is b_i


True True
True False
True True
True False
True True

答案 1 :(得分:0)

这可能不是您正在寻找的答案,但至少它会帮助您理解这个概念。值相同,但索引1和3中的元素因参考而不同。希望这会有所帮助。

import copy

avalues = [(1,1),(2,4),(3,9),(4,16),(5,25)]
bvalues = [(1,1),(2,4),(3,9),(4,16),(5,25)]
a = [avalues[0],avalues[1],avalues[2],avalues[3],avalues[4]]
b = [avalues[0],bvalues[1],avalues[2],bvalues[3],avalues[4]]

print "len(a) == 5:", len(a) == 5
print "len(a) == len(b):", len(a) == len(b)
print "a == b:", a == b
print "a is not b:", a is not b
print "a[0] is b[0]:", a[0] is b[0]
print "a[1] is not b[1]:", a[1] is not b[1]
print "a[2] is b[2]:", a[2] is b[2]
print "a[3] is not b[3]:", a[3] is not b[3]
print "a[4] is b[4]:", a[4] is b[4]