Java's TreeSet equivalent in Python?

后端 未结 6 1923
悲&欢浪女
悲&欢浪女 2020-12-30 22:32

I recently came across some Java code that simply put some strings into a Java TreeSet, implemented a distance based comparator for it, and then made its merry way into the

6条回答
  •  暖寄归人
    2020-12-30 22:51

    If what you want is a set that always iterates in sorted-order, this might get you most of the way there:

    def invalidate_sorted(f):
        def wrapper(self, *args, **kwargs):
            self._sort_cache = None
            return f(self, *args, **kwargs)
        return wrapper
    
    class SortedSet(set):
        _sort_cache = None
    
        _invalidate_sort_methods = """
            add clear difference_update discard intersection_update
            symmetric_difference_update pop remove update
            __iand__ __ior__ __isub__ __ixor__
            """.split()
    
        def __iter__(self):
            if not self._sort_cache:
                self._sort_cache = sorted(set.__iter__(self))
            for item in self._sort_cache:
                yield item
    
        def __repr__(self):
            return '%s(%r)' % (type(self).__name__, list(self))
    
        for methodname in _invalidate_sort_methods:
            locals()[methodname] = invalidate_sorted(getattr(set, methodname))
    

提交回复
热议问题