python - python的交集更新背后的行为
问题描述
我有一本将值映射到集合的字典。我想从我的字典值之一创建一个变量,并与字典中的其他一些值执行集合交集。
当我在这个新变量上调用设置交集更新时,我原来的字典被改变了,有什么想法吗?
似乎 firstElem 指向字典,而不是本身是一个新变量。
exampleDictionary = {'first':{'a','b','c','d'},'second':{'c','d'}}
firstElem = exampleDictionary['first']
firstElem.intersection_update(exampleDictionary['second'])
print(firstElem)
# {'c', 'd'}
print(exampleDictionary)
# {'first': {'c', 'd'}, 'second': {'c', 'd'}}
谢谢
解决方案
你完全正确 -firstElem
确实是对与字典所持有的引用相同的对象的引用。
如果您不希望这种情况发生,您可以只使用该intersection()
方法,它返回一个新集合,而不是intersection_update()
更新到位。
>>> exampleDictionary = {'first':{'a','b','c','d'},'second':{'c','d'}}
>>> firstElem = exampleDictionary['first'].intersection(exampleDictionary['second'])
>>> print(exampleDictionary)
{'first': {'c', 'a', 'b', 'd'}, 'second': {'c', 'd'}}
>>> print(firstElem)
{'c', 'd'}
推荐阅读
- python - 使用 Pyaudio 在 Python 中录音,错误 ||PaMacCore (AUHAL)|| ... msg=音频单元:在当前上下文中无法执行
- angular - 如何理解角度依赖错误报告?
- sql-server - 如何检查安装某些 Windows 服务时创建了哪些数据/列/表(在 MSSQL 中)
- reporting-services - 有没有办法更改 NULLABLE 报告参数的 NULL 文本
- python - 带有两个参数的 Plotly 动画
- typescript - 编译器删除“this”上下文类型约束
- mariadb - 什么是 mariadb 临时文件,例如 /tmp/MYXFhjiU
- xml - 一个根节点
使用 kml 命名空间不会在 basex xquery 中解析 - firebase - FCM - 将服务工作者代码升级到 Firebase 9
- sql - 在子查询中使用外部查询 ID