是否有一个线性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
我还需要实现联合和差异。是否有一个内置的结构来实现这种行为
一个
dict
按插入顺序*并保证键的唯一性。使用普通的dict
并按约定忽略值,或者使用所需的接口创建一个类例如,一个基本的^{}-like 类如下所示:
*从Python 3.6事实上开始,从Python 3.7保证开始
相关问题 更多 >
编程相关推荐