简体   繁体   English

Python.唯一订购商品列表

[英]Python . List of unique ordered items

Is there a lineal python structure that preserves insertion order and uniqueness of elements at the same time?是否存在同时保留元素的插入顺序和唯一性的线性 python 结构? I know that sets preserve uniqueness and list insertion order.我知道集合保留唯一性和列表插入顺序。 By now I will implement this behavior with a class like:到现在为止,我将使用 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 

I also need to implement union and difference.我还需要实施联合和差异。 Is there a built-in structure to achieve this behavior?是否有内置结构来实现此行为?

A dict is insertion ordered* and guarantees uniqueness of keys. dict是按插入顺序* 并保证键的唯一性。 Either use a plain dict and ignore values by convention or create a class with the desired interface.要么使用普通dict并按照惯例忽略值,要么创建具有所需接口的 class。

For example, a basic set -like class would look like this:例如,一个基本set ——如 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

*Since Python 3.6 de-facto and since Python 3.7 guaranteed. *自 Python 以来 3.6 事实上和自 Python 3.7 保证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM