Python OrderedSet 与 .index() 方法

发布于 2024-12-13 07:18:37 字数 125 浏览 2 评论 0原文

有谁知道Python的快速OrderedSet实现:

  • 记住插入顺序
  • 有一个index()方法(就像列表提供的那样)

我发现的所有实现都缺少.index()方法。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一紙繁鸢 2024-12-20 07:18:37

您始终可以将其添加到子类中。以下是您在评论中链接的 OrderedSet 的基本实现:

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")

您提到您只需要 addindex 和按序迭代。您可以通过使用 OrderedDict 作为存储来获取此信息。作为奖励,您可以对 collections.Set 抽象类进行子类化,以获取其他集合操作 frozenset 的支持:

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 进行子类化 code> 因为您不支持从集合中删除元素并保持索引正确。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文