Py学习  »  Python

python中列表追加的差异

AlwaysNull • 3 年前 • 1150 次点击  

当我使用时,我得到了一个不同的结果 append(path) 与。 append(list(path))

我有以下代码来查找求和的所有路径:

class TreeNode:
  def __init__(self, val, left=None, right=None):
    self.val = val
    self.left = left
    self.right = right


def find_paths(root, sum):
  allPaths = []
  
  dfs(root, sum, [], allPaths)

  return allPaths

def dfs(root, sum, path, res):
  if not root:
    return
  
  path.append(root.val)
  if root.val == sum and root.left is None and root.left is None:
    res.append(path)
  
  dfs(root.left, sum - root.val, path, res)
  dfs(root.right, sum - root.val, path, res)

  del path[-1]
  

def main():

  root = TreeNode(12)
  root.left = TreeNode(7)
  root.right = TreeNode(1)
  root.left.left = TreeNode(4)
  root.right.left = TreeNode(10)
  root.right.right = TreeNode(5)
  sum = 23
  print("Tree paths with sum " + str(sum) +
        ": " + str(find_paths(root, sum)))


main()

它有以下输出:

Tree paths with sum 23: [[], []]

但如果我换了 res.append(path) res.append(list(path)) 然后返回正确答案 Tree paths with sum 23: [[12, 7, 4], [12, 1, 10]] .我不明白为什么要使用 list 手术会改变答案。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133149
 
1150 次点击  
文章 [ 2 ]  |  最新文章 3 年前
John Gordon
Reply   •   1 楼
John Gordon    3 年前

res.append(path) 附加实际的 path 对象,而不是它的副本。所以如果 路径 更改之后,更改将显示在 res 而且

res.append(list(path)) 附加一份副本。

j1-lee
Reply   •   2 楼
j1-lee    3 年前

res.append(path) 附加对象 path 把自己列入名单 res .在那一行之后,当你修改 路径 对象(比如 del path[-1] ),修改也将应用于中的附加对象 物件 因为它们是同一个物体。

list(path) 另一方面,“复制”了 路径 .所以这一个现在是不同于 路径 .当你修改 路径 之后,修改不会传播到这个不同的对象。

如果你这样做,你会得到同样的结果 path[:] path.copy() 而不是 列表(路径) .