gurobi 構建了一個元組串列類。看這里。 它說這是 Python 串列類的自定義子類,旨在允許您從元組串列中有效地構建子串列。更具體地說,您可以對元組串列物件使用 select 方法來檢索與特定欄位中的一個或多個指定值匹配的所有元組。我已經測驗了它的 select 方法,它非常有效。有誰知道如何實作像 gurobi 這樣的元組串列?
uj5u.com熱心網友回復:
最簡單的解決方案是將串列與元組中的每個條目的 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)]
uj5u.com熱心網友回復:
# 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://www.uj5u.com/qianduan/348944.html
上一篇:如何在顫振中顯示串列中的影像
