gurobi构建一个tuplelist类,看这里。表示这是Python类的一个自定义子类,它允许您从一个元组列表中高效地构建子列表。更具体地说,可以使用tuplelist对象上的select方法检索所有在特定字段中匹配一个或多个指定值的元组。我已经测试过它的选择方法,它非常有效。有人知道如何像gurobi那样实现tuplelist类吗?
发布于 2021-11-03 08:39:20
最简单的解决方案将是将列表与元组中的每个条目进行配对。dict的键是一个元组值。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)]发布于 2021-11-03 07:57:32
# 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")https://stackoverflow.com/questions/69821330
复制相似问题