首页 > 解决方案 > Python set update() 是否替换现有项目?

问题描述

如果我使用my_set.update(my_list)where some elements my_listare ==existing elements in my_set,它是否会替换现有项目?

标签: python-3.xset

解决方案


它没有:

from dataclasses import dataclass
@dataclass(frozen=True)
class MyType:
    hashed: int
    not_hashed: str
    def __eq__(self, other):
        return hash(self) == hash(other)
    def __hash__(self):
        return hash((self.hashed, ))

x = {MyType(hashed=1, not_hashed="original")}
x.update([MyType(1, "new")])
print(x)

# {MyType(hashed=1, not_hashed='original')} 


推荐阅读