热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

python中setindex_PythonOrderedSet与.index()方法

DoesanyoneknowaboutafastOrderedSetimplementationforpythonthat:remembersinsertionorderhasan

Does anyone know about a fast OrderedSet implementation for python that:

remembers insertion order

has an index() method (like the one lists offer)

All implementations I found are missing the .index() method.

解决方案

You can always add it in a subclass. Here is a basic implementation for the OrderedSet you linked in a comment:

class IndexOrderedSet(OrderedSet):

def index(self, elem):

if key in self.map:

return next(i for i, e in enumerate(self) if e == elem)

else:

raise KeyError("That element isn't in the set")

You mentioned you only need add, index, and in-order iteration. You can get this by using an OrderedDict as storage. As a bonus, you can subclass the collections.Set abstract class to get the other set operations frozensets support:

from itertools import count, izip

from collections import OrderedDict, Set

class IndexOrderedSet(Set):

"""An OrderedFrozenSet-like object

Allows constant time 'index'ing

But doesn't allow you to remove elements"""

def __init__(self, iterable = ()):

self.num = count()

self.dict = OrderedDict(izip(iterable, self.num))

def add(self, elem):

if elem not in self:

self.dict[elem] = next(self.num)

def index(self, elem):

return self.dict[elem]

def __contains__(self, elem):

return elem in self.dict

def __len__(self):

return len(self.dict)

def __iter__(self):

return iter(self.dict)

def __repr__(self):

return 'IndexOrderedSet({})'.format(self.dict.keys())

You can't subclass collections.MutableSet because you can't support removing elements from the set and keep the indexes correct.



推荐阅读
author-avatar
qaz9
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有