如何在 python 中构建元组列表 class 搜索时效率高?

how to build a tuplelist class in python whch is efficient when searching?

gurobi 构建一个元组列表class。see here. 它说 This is a custom sub-class of the Python list class 旨在让您从元组列表中有效地构建子列表。更具体地说,您可以在元组列表对象上使用 select 方法来检索与特定字段中的一个或多个指定值匹配的所有元组。 我已经测试了它的 select 方法,它非常有效。有谁知道如何实现像 gurobi 那样的元组列表 class?

# Search function with parameter list name
# and the value to be searched
def search(Tuple, n):

    for i in range(len(Tuple)):
        if Tuple[i] == n:
            return True
    return False

# list which contains both string and numbers.
Tuple= (1, 2, 'sachin', 4, 'Geeks', 6)


# Driver Code
n = 'Geeks'

if search(Tuple, n):
    print("Found")
else:
    print("Not Found")

最简单的解决方案是将列表与元组中每个条目的字典配对。字典的键是一个元组值。 dict 的值是列表中的一组索引。像这样:

class TupleList:
    def __init__(self):
        self.lst = []
        self.dictlist = []

    def append(self, tup):
        dictlist = self.dictlist
        if dictlist and len(tup) != len(dictlist):
            raise ValueError("All tuples must have same length")
        lst = self.lst
        tupidx = len(lst)
        lst.append(tup)
        if not dictlist: # first entry
            self.dictlist = [{entry: set((tupidx,))} for entry in tup]
            return
        for entry, dict_ in zip(tup, dictlist):
            set_ = dict_.setdefault(entry, set())
            set_.add(tupidx)

    def select(self, *args):
        # TODO: Implement '*' wildcard
        dictlist = self.dictlist
        if not dictlist:
            return []
        if len(dictlist) != len(args):
            raise KeyError("Wrong number of tuple values")
        tupsets = (dict_[arg] for dict_, arg in zip(dictlist, args))
        try:
            intersect = next(tupsets)
            for tupset in tupsets:
                intersect = intersect.intersection(tupset)
        except KeyError: # value not present
            return []
        lst = self.lst
        return [lst[idx] for idx in sorted(intersect)]