Python OrderedSet与.index()方法 [英] Python OrderedSet with .index() method
问题描述
是否有人知道针对python的快速OrderedSet实现:
Does anyone know about a fast OrderedSet implementation for python that:
- 记住插入顺序
- 具有index()方法(如一个清单所提供的)
我发现的所有实现都缺少.index()方法.
All implementations I found are missing the .index() method.
推荐答案
您始终可以将其添加到子类中.这是您在评论中链接的OrderedSet
的基本实现:
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")
您提到您只需要add
,index
和有序迭代.您可以通过使用OrderedDict
作为存储来获得此功能.另外,您可以子类化collections.Set
抽象类以获得其他set操作frozenset
的支持:
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 frozenset
s 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())
您不能继承collections.MutableSet
的子类,因为您不支持从集合中删除元素并保持索引正确.
You can't subclass collections.MutableSet
because you can't support removing elements from the set and keep the indexes correct.
这篇关于Python OrderedSet与.index()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!