gpt4 book ai didi

python - list = [] 与 list.clear() 之间的区别

转载 作者:行者123 更新时间:2023-11-28 19:36:35 25 4
gpt4 key购买 nike

list = []list.clear() 有什么区别?

根据我的代码行为和我自己的观察,list.clear() 删除了它的条目以及我用来附加其数据的条目。

例子:

container.append(list)
list.clear()

container 也将是 []

最佳答案

调用 clear 从列表中删除所有元素。分配 [] 只是将该变量替换为另一个空列表。当您有两个变量指向同一个列表时,这一点就很明显了。

考虑以下片段:

>>> l1 = [1, 2, 3]
>>> l2 = l1
>>> l1.clear()
>>> l1 # l1 is obviously empty
[]
>>> l2 # But so is l2, since it's the same object
[]

与这个相比:

>>> l1 = [1, 2, 3]
>>> l2 = l1
>>> l1 = []
>>> l1 # l1 is obviously empty
[]
>>> l2 # But l2 still points to the previous value, and is not affected
[1, 2, 3]

关于python - list = [] 与 list.clear() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55897375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com