欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python合并列表重新排序_python – 将两个已排序的列表合并为一个更大的排序列表...

发布时间:2025/3/20 python 28 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python合并列表重新排序_python – 将两个已排序的列表合并为一个更大的排序列表... 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

我正在尝试创建一个合并函数,将在我正在进行的合并排序中使用.

我遇到了一些麻烦,我似乎无法找到错误.

我评论它试图向你们展示我的思考过程:

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合并列表重新排序_python – 将两个已排序的列表合并为一个更大的排序列表...的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。