python - 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 中?
谢谢!
解决方案
推荐阅读
- node.js - 如何使用 BigQuery nodejs 客户端库中的 BigQueryDate 类?
- c++ - 更新 RichEdit20A 时如何阻止 CDialog(mfc) 在 Invalidate 上闪烁
- sql-server - SQL Server 似乎可以正确解释不受支持的字符串文字格式
- shell - 在 tcl 中,我如何写入我所在的 shell 中的变量?
- python-3.x - 使用python3从树莓派通过串口发送二进制数据会导致垃圾
- c - 在普通 C(msvc) 中模拟 lambdas - 递归 lambdas
- pyspark-sql - 在相等且相同的分区中拆分字符串值
- javascript - 如何使用 AJAX 将数据从输入乘以数据库中的数据
- c# - 为什么需要将值传递给 Tuple 构造函数?
- java - JMeter 测试中 CXF 的不连贯行为