Python 追加函数未按预期工作

标签 python

我正在尝试使用附加函数将列表附加到列表。请参阅下面的代码 - temp 将是动态创建的临时列表。我想将 temp 附加到 list1。

temp = []
list1 = []
for num in range(0,2):
    temp.clear()
    temp.append(num)
    list1.append(temp)
    print(list1)

list1 中的预期输出是 [[0],[1]]。但是我得到[[1],[1]]。 有人可以解释一下这背后的原因吗?追加应追加到列表而不更改列表。

最佳答案

由于您已附加整个 temp 列表,因此 list1 包含对该列表的引用。因此,当您使用 temp.clear()temp.append(num) 修改 temp 时,list1 也会被修改。如果您不希望发生这种情况,则需要附加一份副本:

import copy
temp = []
list1 = []
for num in range(0,2):
    temp.clear()
    temp.append(num)
    list1.append(copy.copy(temp))
    print(list1)
> [[0]]
> [[0], [1]]

获得所需结果的另一种方法是使用 temp = [] 而不是 temp.clear()。这将使 temp 指向内存中的一个新对象,而使 list1 中引用的对象保持不变。两者都有效!

关于Python 追加函数未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62226594/

相关文章:

python - 无法在 Jupyter 笔记本中运行 tf.enable_eager_execution()

list - 以 pythonic 方式创建列表列表

python - django-tables2 复选框列名

python - 在 PyTorch 中,当 GPU 张量被分配一个新值时,GPU 内存是否被释放?

python - 如何从VLC媒体播放器获取帧

python - python 3.6中的attrgetter函数

python - 根据另一个字符串列表对字符串列表进行排序

python - 无法在 Linux Ubuntu 上安装 mysqlclient-python

python - 获取完整的包模块名称

python - jupyter 笔记本到 python 脚本,无需更改格式