【问题标题】:Whats the difference Between += and .append()? [duplicate]+= 和 .append() 有什么区别? [复制]
【发布时间】:2020-07-14 08:52:08
【问题描述】:

我试图在没有递归的情况下执行 BST 的中序遍历。

在特定的代码行我遇到了错误,代码:

最初我定义为:

out=[]

elif stack!=[]:
current=stack.pop()
out+=(current.val)
current=current.right

Error: 
Traceback (most recent call last):
  File "main.py", line 224, in 
    Z = obj.inorderTraversal(A)
  File "/tmp/judge/solution.py", line 16, in inorderTraversal
    out+=(current.val)
TypeError: 'int' object is not iterable

然后我改变了 out+=(current.val) 到 out.append(current.val),它起作用了。

谁能帮我理解这个??

基本上,这两种说法的区别是什么??

【问题讨论】:

    标签: python python-3.x binary-search-tree inorder


    【解决方案1】:

    使用 append 可以指定插入一个元素,使用 += 可以连接两个列表。详情请见https://docs.python.org/3/tutorial/datastructures.html

    在这种情况下,您将 += 与 int 一起使用,正确的语法是 out += [current.val]out.append(current.val)(更具可读性)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      • 2015-11-23
      • 2013-02-13
      • 2011-04-26
      • 2016-09-24
      相关资源
      最近更新 更多