列表添加和;在python中列出append和list变量范围
我正在解决LeetCode问题(link-)。基本上,问题是找到给定二叉树中的所有路径 1 / \ 2 3 \ 5 考虑下面的二叉树 1 / \ 2 3 \ 5 上面提到的代码运行良好。但也有如下微妙之处列表添加和;在python中列出append和list变量范围,python,python-2.7,tree,Python,Python 2.7,Tree,我正在解决LeetCode问题(link-)。基本上,问题是找到给定二叉树中的所有路径 1 / \ 2 3 \ 5 考虑下面的二叉树 1 / \ 2 3 \ 5 上面提到的代码运行良好。但也有如下微妙之处 如果我将ls=ls+[root.val]更改为ls.append(root.val)调用dfs后,函数binaryTreePaths中的res将变为 [[],[]] 在上述相同的情况下,在函数dfs中,我得到的不是[[1,2,5],[1,3]],而是[
- 如果我将
更改为ls=ls+[root.val]
调用ls.append(root.val)
后,函数dfs
中的binaryTreePaths
将变为res
[[],[]]
- 在上述相同的情况下,在函数
中,我得到的不是dfs
,而是[[1,2,5],[1,3]]
[[1,3],[1,3]]
res的值
这到底是怎么回事 根据代码,
ls
不属于任何类型,实际上不存在,因为您正在初始化它,因此它会给出一个错误,.append
不存在ls=ls+[root.val]
等于ls=[root.val]
。因此它是有效的
希望这有帮助!:) 这是您的实现--没有不必要的类--: 这是输出
In [1]: tree = Node(1, Node(2, None, Node(5)), Node(3))
In [2]: res = []
In [3]: dfs(tree, [], res)
In [4]: res
Out[4]: [[1, 2, 5], [1, 3]]
太好了!它起作用了。这里有。追加:
def dfs(root, ls, res):
if root == None:
return
ls.append(root.val)
if not root.left and not root.right:
res.append(ls)
if root.left:
dfs(root.left, ls, res)
if root.right:
dfs(root.right, ls, res)
但是现在,这一次
In [7]: res = []
In [8]: dfs(tree, [], res)
In [9]: res
Out[9]: [[1, 2, 5, 3], [1, 2, 5, 3]]
不太好。请注意,两个列表共享所有内容。。。几乎就好像它们是同一个列表:
啊哈!他们是同一张名单
第一次实施之所以有效,是因为以下几行:
ls + [root.val]
创建一个新列表(这就是为什么您必须将其重新分配给ls
),而:
ls.append(root.val)
在适当位置对列表进行变异
In [20]: print(hex(id(x)))
0x104216288
In [21]: x.append(4)
In [22]: x
Out[22]: [1, 2, 3, 4]
In [23]: print(hex(id(x)))
0x104216288
但是看看当我们使用+
操作符时会发生什么:
In [24]: x = [1, 2, 3]
In [25]: print(hex(id(x)))
0x1042c8308
In [26]: x = x + [4]
In [27]: print(hex(id(x)))
0x104222588
如果我们先复制列表,我们可以使用append
In [29]: def dfs(root, ls, res):
...: if root == None:
...: return
...: copy = ls[:]
...: copy.append(root.val)
...: if not root.left and not root.right:
...: res.append(copy)
...: if root.left:
...: dfs(root.left, copy, res)
...: if root.right:
...: dfs(root.right, copy, res)
...:
In [30]:
In [30]: res = []
In [31]: dfs(tree, [], res)
In [32]: res
Out[32]: [[1, 2, 5], [1, 3]]
为了完整性起见,使用增广赋值运算符,例如some\u list+=另一个\u list
修改列表,本质上等同于some\u list.extend(另一个\u list)
In [24]: x = [1, 2, 3]
In [25]: print(hex(id(x)))
0x1042c8308
In [26]: x = x + [4]
In [27]: print(hex(id(x)))
0x104222588
In [29]: def dfs(root, ls, res):
...: if root == None:
...: return
...: copy = ls[:]
...: copy.append(root.val)
...: if not root.left and not root.right:
...: res.append(copy)
...: if root.left:
...: dfs(root.left, copy, res)
...: if root.right:
...: dfs(root.right, copy, res)
...:
In [30]:
In [30]: res = []
In [31]: dfs(tree, [], res)
In [32]: res
Out[32]: [[1, 2, 5], [1, 3]]
In [38]: x = [1, 2, 3, 4]
In [39]: print(hex(id(x)))
0x1045e5d08
In [40]: x += [5]
In [41]: x
Out[41]: [1, 2, 3, 4, 5]
In [42]: print(hex(id(x)))
0x1045e5d08