2014-04-04 163 views
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 
+0

你有沒有使用這種算法? – msvalkon

+0

如果你真的想重新發明輪子(運動或其他),我通常會建議將你的算法分解成更多可管理的組件並單獨測試它們。否則,請使用@ msvalkon的建議。 – aepsil0n

+0

不,但我必須將所有「候選人」保存在列表中,並使用它們來獲取新合併列表中的下一個元素。這就是爲什麼使用'排序'不是很有用。 – user3484165

回答

0

如何:

merged = lst_of_lsts[-1] 
for lst in lst_of_lsts[0:-1]: 
    merged += lst 
merged.sort() 
相關問題