0
我被要求使用一个列表来保存所有候选项,以便将最终输出列表旁边的所有候选项移动到一个排序列表中。我写了这段代码,并得到索引错误。任何人都可以帮忙!将列表的列表合并到一个列表中python
import copy
def getNext(lst, index):
if len(lst)< index+1:
return None
else:
return lst[index]
def multi_merge_v2(lst_of_lsts):
myLst= copy.copy(lst_of_lsts)
candidates=[]
for lst in myLst:
if lst!=[]:
candidates.append(lst[0])
indexes= [0]*len(candidates)
merged=[]
while candidates !=[]:
Min = min(candidates)
merged += [Min]
index = indexes[candidates.index(Min)]
indexes[index]+=1
nextCan = getNext(myLst[index], indexes[index])
if nextCan == None:
myLst.remove(myLst[index])
candidates.remove(Min)
indexes.remove(indexes[index])
else:
candidates[index]=nextCan
return merged
你有没有使用这种算法? – msvalkon
如果你真的想重新发明轮子(运动或其他),我通常会建议将你的算法分解成更多可管理的组件并单独测试它们。否则,请使用@ msvalkon的建议。 – aepsil0n
不,但我必须将所有“候选人”保存在列表中,并使用它们来获取新合并列表中的下一个元素。这就是为什么使用'排序'不是很有用。 – user3484165