python唯一订购项目列表

2024-09-27 07:27:56 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有一个线性python结构,它可以同时保持元素的插入顺序和唯一性?我知道集合保留唯一性和列表插入顺序。现在,我将使用如下类实现此行为:

class OrderedUniqueContainer:
    
    def __init__(self):
        self._data = []

    def add(self, object):
        # Assuming object has neccesary __hash__ and __eq__
        if object not in self._data:
            self._data.append(object) 

    def remove(self, object):
        try:
            self._data.remove(object)
        except ValueError:
            pass 

我还需要实现联合和差异。是否有一个内置的结构来实现这种行为


Tags: selfadd元素列表dataobject顺序init
1条回答
网友
1楼 · 发布于 2024-09-27 07:27:56

一个dict按插入顺序*并保证键的唯一性。使用普通的dict并按约定忽略值,或者使用所需的接口创建一个类

例如,一个基本的^{}-like类如下所示:

class OrderedUniqueContainer:
    """Set-like container of unique items maintaining insertion order"""
    def __init__(self, initial=()):
        self._data = dict.fromkeys(initial)

    def copy(self):
        """Return a shallow copy of the set."""
        clone = type(self)()
        clone._data = self._data.copy()
        return clone

    def add(self, item):
        """Add element `item` to the set."""
        self._data[item] = None

    def discard(self, item):
        """Remove element `item` from the set if it is present."""
        self._data.pop(item, None)

    def update(self, *others: 'OrderedUniqueContainer'):
        """Update the set, adding elements from all others."""
        for other in others:
            self._data.update(other._data)

    def union(self, *others: 'OrderedUniqueContainer'):
        """Return a new set with elements from the set and all others."""
        clone = self.copy()
        clone.update(*others)
        return clone

    # additional desired methods

*从Python 3.6事实上开始,从Python 3.7保证开始

相关问题 更多 >

    热门问题