python - 为什么 + 运算符不更改列表而 .append() 会更改列表?

标签 python list append concatenation

我正在研究 Udacity,Dave Evans 介绍了一个关于列表属性的练习

list1 = [1,2,3,4]
list2 = [1,2,3,4]

list1=list1+[6]
print(list1)
list2.append(6)
print(list2)

list1 = [1,2,3,4]
list2 = [1,2,3,4]

def proc(mylist):
    mylist = mylist + [6]

def proc2(mylist):
    mylist.append(6)

# Can you explain the results given by the four print statements below? Remove
# the hashes # and run the code to check.

print (list1)
proc(list1)
print (list1)

print (list2)
proc2(list2)
print (list2)

输出是

[1, 2, 3, 4, 6]
[1, 2, 3, 4, 6]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4, 6]

所以在函数中,向集合中添加 6 不会显示,但在不在函数中时会显示?

最佳答案

So in a function the adding a 6 to the set doesn't show but it does when not in a function?

不,事实并非如此。

发生的事情是,当您执行 mylist = mylist + [6] 时,您实际上是在创建一个全新的列表并将其放入本地 mylist 变量中。此 mylist 变量将在函数执行后消失,新创建的列表也将消失。

OTOH 当您执行 mylist.append(6) 时,您不会创建新列表。您已在 mylist 变量中获得该列表,并将新元素添加到同一列表中。结果是列表(也由 list2 指向)将自行更改。 mylist 变量将再次消失,但在这种情况下,您更改了原始列表。

让我们看看更直观的解释是否可以帮助您:)

调用 proc() 时会发生什么

当您编写 list1 = [1, 2, 3, 4, 5] 时,您正在创建一个新的列表对象(在等号的右侧)并创建一个新变量,list1,它将指向这个对象。

Creating new list instance and global variable

然后,当您调用 proc() 时,您创建了另一个新变量 mylist,并且由于您将 list1 作为参数传递,mylist 将指向同一个对象:

Calling method creates local variable

但是,操作mylist + [6] 创建了一个全新的列表对象,其内容是mylist 指向的对象的内容加上以下列表对象的内容 - 即 [6]。由于您将这个新对象归因于 mylist,我们的场景发生了一些变化,mylist 不再指向 list1 指向的同一个对象:

mylist points to new list object

我没有说的是 mylist 是一个局部变量:它会在 proc() 函数结束后消失。所以,当 proc() 执行结束时,mylist 就消失了:

mylist is gone

由于没有其他变量指向由 mylist + [6] 生成的对象,它也会消失(因为垃圾收集器*将收集它):

GC collects the list

注意,最后list1指向的对象并没有改变。

调用 proc2() 时会发生什么

当您调用 proc2() 时,一切都会改变。首先,它是同一件事:您创建一个列表...

Creating new list instance and global variable

...并将其作为参数传递给一个函数,该函数将生成一个局部变量:

Calling method creates local variable

但是,您不是使用生成新列表的 + 连接运算符,而是将 append() 方法应用于现有列表。 append() 方法不会创建新对象;相反,它_changes 现有的:

Appending a value to a list

函数结束后,局部变量会消失,但它和list1指向的原始对象已经改变:

It is still altered

由于它仍然被list1指向,所以原始列表没有被破坏。

编辑:如果您想看看在您眼前发生的所有这些事情,请转到this radically amazing simulator。 :

enter image description here

* 如果您不知道什么是垃圾收集器...好吧,理解您自己的问题后您很快就会发现。

关于python - 为什么 + 运算符不更改列表而 .append() 会更改列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10748158/

相关文章:

python - flask-jwt 如何处理 token ?

python - 列表理解结构等效于循环示例

list - 如何在 Kotlin 中并行迭代两个列表?

objective-c - iOS - 将文本 append 到应用程序包中的文件

python - 使用 Python 和 imaplib 的 GMail - 在 "All mail"中搜索

python - 如何使用groupby对象获取其他列的总和?

python - Python 中的属性错误 : 'list' object has no attribute 'split'

java - 是否有用于列表复杂处理的 Java API?

python - 使用相同的索引 pandas 按行合并两个数据帧

swift - 在 uibutton 上单击 UITableView 中的 reloadData - swift