首页 > 解决方案 > Python函数在被调用之前执行

问题描述

我正在尝试将新的唯一值添加到 Python 中的列表中,然后检查是否有任何新值实际添加到列表中。这是我从更大的程序中提取的代码片段,足以复制我遇到的问题。

from collections import Counter


def expand_list(existing_list, new_list):
    for elem in new_list:
        if elem not in existing_list:
            existing_list.append(elem)
    return existing_list


c1 = [1, 2]
c2 = [3, 4, 5]

b = c1
expand_list(c1, c2)

print(c1)
print(b)
print(Counter(b) != Counter(c1))

当我执行这是结果

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
False

出于某种原因,我无法理解 c1 在复制到 b 之前已更改,即使在我使用 c1 中的值创建 b 之后调用了该函数。

这是我运行此代码时的预期

[1, 2, 3, 4, 5]
[1, 2]
True

有人可以向我解释为什么会发生这种情况,以及如何在函数修改 c1 之前成功地将其保存到 b 中?

谢谢!

标签: pythonlistfunction

解决方案


推荐阅读