【问题标题】:difference between clear list and list = []清除列表和列表之间的区别 = []
【发布时间】:2022-01-01 02:45:49
【问题描述】:

我目前正在研究一位同事以前写的一些脚本,我的学士论文需要它们。

当我编写另一个脚本时,我遇到了以下问题:

  listA = [......] #list is filled
  listB = listA
  listB.clear()

在这个 listA 也被清除后,我开始使用它:

  listB = listA.copy()

我的同事在她的代码中这样做了

 listA = [.......] #list is filled
 listB = listA
     functoin(listB)
 listB = []

在那之后,她仍然以从未被清空过的方式使用 listA。但是由于 python 通过引用复制并不意味着命令:

 listB = []

现在 listA 也是空的吗?

提前致谢

【问题讨论】:

  • listB = [] 使名称 listB 指向一个新的空列表对象。之后它不再链接到listA
  • “我的同事”代码不是有效的 Python。
  • 如果你想要一个新的空列表,为什么要分配listB = listA根本

标签: python scripting


【解决方案1】:

需要明确的是,当您运行同事的代码时,会发生以下情况:

listA = [.......] # listA points to a list

listB = listA     # listB and listA are now 2 variables pointing to the SAME OBJECT

function(listB)   # this does the same as function(listA) would do
                  # only the object matters here, the function does not know the variable name

listB = []        # now listB points to a new object, an empty list.
                  # listA and the object to which it points remain the same

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    相关资源
    最近更新 更多