python 集合是有序的吗_Python有序集吗?

有序集在功能上是有序字典的特例。

字典的键是独一无二的。因此,如果忽略有序字典中的值(例如,通过赋值)None),则基本上有一个有序集。

截至Python3.1的确有collections.OrderedDict..下面是OrderedSet的示例实现。(请注意,只需要定义或重写几个方法:collections.OrderedDict和collections.MutableSet(做重物。)import collectionsclass 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__)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值