Python。唯一订购商品列表

Python . List of unique ordered items

是否存在同时保留元素的插入顺序和唯一性的线性python结构?我知道集合保留唯一性和列表插入顺序。到现在为止,我将使用 class 实现此行为,例如:

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 

我还需要实现并集和差集。是否有内置结构来实现此行为?

A dict 是按插入顺序*并保证键的唯一性。要么使用普通 dict 并按照惯例忽略值,要么创建具有所需界面的 class。

例如,基本的 set-like class 看起来像这样:

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 保证。