将列表合并到一个列表python中

2024-10-03 13:20:55 发布

您现在位置: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

Tags: 列表indexreturnif排序defmergedmin