添加重复项时从集合中获取原始元素

吉丁·科甸

我有一个Set存储IP地址的地址。IP地址可以是唯一IP或子网。我已经重载了__hash____eq__方法。Set工作正常。

问题是:当我尝试添加重复元素时,是否可以显示原始元素?

我无法使用该in操作,因为要花很长时间,因为大约有100,000个IP地址,因此我只能为该对象创建5个不同的存储桶Set

一个例子

我将子网10.0.0.0/8添加到Set

然后,我尝试将唯一的IP 10.10.10.10添加到Set

Set,因为它是集10.0.0.0/8的副本将不添加唯一的IP。在这种情况下,我想向用户显示:

10.10.10.10重复的10.0.0.0/8

PS:我只是对in操作进行了定义它仅显示该元素是否已经存在。它不会显示原始元素。(我不是python开发人员)。

PPS:我正在阅读防火墙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)}

如果没有新商品,您将进行两次查找。

编辑:交集将始终返回较小集合的成员,请参见此处因此,您可以改用以下方法:

def isolate(new_item, existing_set):
    for item in existing_set:
        if item == new_item:
            return item

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章