假设有如下代码:
A = 10
tmpA = A
print id(A),id(tmpA)
可以看到,id(A)与id(tmpA)相同。这意味着执行 tmpA = A的时候,电脑并未给A赋予一块新的地址,而是让tmpA指向A的存储地址。
可以通过下面的方法得到A的拷贝:
import copy
A = 10
tmpA = copy.copy(A)
print id(A),id(tmpA)
得到的A,tmpA的id不同。
下面用一个leetcode的例子说明拷贝的重要性。
Given a binary tree containing digits from 0-9
only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3
which represents the number 123
.
Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path 1->2
represents the number 12
.
The root-to-leaf path 1->3
represents the number 13
.
Return the sum = 12 + 13 = 25
.
代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import copy
class Solution(object):
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return self.excute(root,0)
def excute(self,root,Sum):
tmpSum = copy.copy(Sum) #这里必须用copy的方法,否则在不同的迭代周期中,Sum的值都有可能被改变。
if not root.left and not root.right:
return 10*tmpSum+root.val
elif root.left and not root.right:
return self.excute(root.left,10*tmpSum+root.val)
elif root.right and not root.left:
return self.excute(root.right,10*tmpSum+root.val)
else:
return self.excute(root.left,10*tmpSum+root.val)+self.excute(root.right,10*tmpSum+root.val)
另外,copy分为copy.copy() 和 copy.deepcopy(),具体不同请参考这篇 文章。