首页 > 解决方案 > 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'}}

谢谢

标签: pythondictionaryset

解决方案


你完全正确 -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'}

推荐阅读