Python是否有序集?

发布于 2021-02-02 23:22:45

Python有一个有序的字典。有序套呢?

关注者
0
被浏览
98
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    为此,有一个有序的设置(可能的新链接)配方,可从Python 2文档中引用。它可以在Py2.6或更高版本以及3.0或更高版本上运行,而无需进行任何修改。该接口几乎与普通集合完全相同,不同之处在于初始化应使用列表进行。

    OrderedSet([1, 2, 3])
    

    这是一个MutableSet,因此for的签名.union与set 的签名不匹配,但是由于它包含__or__类似的内容,因此可以轻松添加:

    @staticmethod
    def union(*sets):
        union = OrderedSet()
        union.union(*sets)
        return union
    
    def union(self, *sets):
        for set in sets:
            self |= set
    


  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    从功能上说,有序集是有序字典的特例。
    字典的键是唯一的。因此,如果人们不理会有序字典中的值(例如,通过分配它们None),那么实质上就是一个有序集合。

    对于Python 3.1的存在collections.OrderedDict。以下是OrderedSet的示例实现。(请注意,只有很少的方法需要定义或重写:collections.OrderedDict和collections.MutableSet。做繁重)

    import collections
    
    class OrderedSet(collections.OrderedDict, collections.MutableSet):
    
        def update(self, *args, **kwargs):
            if kwargs:
                raise TypeError("update() takes no keyword arguments")
    
            for s in args:
                for e in s:
                     self.add(e)
    
        def add(self, elem):
            self[elem] = None
    
        def discard(self, elem):
            self.pop(elem, None)
    
        def __le__(self, other):
            return all(e in other for e in self)
    
        def __lt__(self, other):
            return self <= other and self != other
    
        def __ge__(self, other):
            return all(e in self for e in other)
    
        def __gt__(self, other):
            return self >= other and self != other
    
        def __repr__(self):
            return 'OrderedSet([%s])' % (', '.join(map(repr, self.keys())))
    
        def __str__(self):
            return '{%s}' % (', '.join(map(repr, self.keys())))
    
        difference = property(lambda self: self.__sub__)
        difference_update = property(lambda self: self.__isub__)
        intersection = property(lambda self: self.__and__)
        intersection_update = property(lambda self: self.__iand__)
        issubset = property(lambda self: self.__le__)
        issuperset = property(lambda self: self.__ge__)
        symmetric_difference = property(lambda self: self.__xor__)
        symmetric_difference_update = property(lambda self: self.__ixor__)
        union = property(lambda self: self.__or__)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看