我有一个存储 IP 地址的 Set
。 IP 地址可以是唯一的 IP 或子网。我重载了 __hash__
和 __eq__
方法。 Set
工作正常。
问题是:当我尝试添加重复元素时,有没有办法显示原始元素?
我不能使用 in
操作,因为它需要很长时间,因为大约有 100,000 个 IP 地址,而且我只能为 Set
创建大约 5 个不同的存储桶。
一个例子
我将子网 10.0.0.0/8 添加到 Set
。
然后我尝试将唯一 IP 10.10.10.10 添加到 Set
。
Set
不会添加唯一 IP,因为它是子集 10.0.0.0/8 的副本。在这种情况下,我想向用户展示:
10.10.10.10 duplicate of 10.0.0.0/8
P.S : 我刚刚完成了 in
操作的定义。它只是显示元素是否已经存在。它不会显示原始元素。 (我不是 Python 开发人员)。
P.P.S:我正在阅读防火墙 ACL 列表。我添加的不仅仅是将 IP 地址添加到集合中。这就是为什么我不能在这里显示代码。代码有效。
最佳答案
您可以查看 IP 地址集和仅包含您要添加到该集中的项目的新集的交集。
class MyClass:
def __init__(self, name):
self.name = name
def __repr__(self):
return 'MyClass({})'.format(self.name)
def __eq__(self, other):
return isinstance(other, MyClass)
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return 0
existing_set = {MyClass('existing')}
new_item = MyClass('new')
intersection = {new_item}.intersection(existing_set)
if intersection:
print('{} duplicate of {}'.format(new_item, intersection.pop()))
# MyClass(new) duplicate of MyClass(existing)
else:
existing_set.add(new_item)
print(existing_set)
# {MyClass(existing)}
如果新项目不在集合中,您将进行两次查找。
编辑:交集总是返回较小集合的成员,参见 here .因此,您可以改用此方法:
def isolate(new_item, existing_set):
for item in existing_set:
if item == new_item:
return item
关于python - 添加重复项时从集合中获取原始元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41057186/