gpt4 book ai didi

python - 将两个排序列表合并为一个更大的排序列表

转载 作者:太空狗 更新时间:2023-10-30 00:44:34 25 4
gpt4 key购买 nike

我正在尝试制作一个合并函数,该函数将用于我正在制作的合并排序。

我遇到了一些麻烦,我似乎找不到错误。

我评论它是为了向你们展示我的思考过程:

def merge(aList, bList):
newList = []
while (len(aList) > 0) & (len(bList) > 0): #Loop until both lists are empty
if aList[0] < bList[0]: #If the first item of aList is smaller than the first item of bList
newList.append(aList[0]) #add that item to the new list
aList.pop(0) #and remove it from the original list

else: #If it gets here, that means the first item of bList was smaller
newList.append(bList[0]) #So put the first item of bList is the new list
bList.pop(0) #and remove it from the original
return newList

list1 = [3, 4, 8, 9]
list2 = [1, 2, 5, 8]

print(merge(list1, list2))
print(list1)
print(list2)

输出:

[1, 2, 3, 4, 5, 8]
[8, 9]
[0]

我原以为 list1 和 list2 是空的,但由于某种原因,list1 中似乎有一个未放置的 8 和 9。有人有想法吗?

最佳答案

这是一个使用 Python 库的版本 heapq :

import heapq

def merge(aList, bList)
return list(heapq.merge(aList, bList))

关于python - 将两个排序列表合并为一个更大的排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28245942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com