本文介绍了将两个排序列表以降序合并为一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经能够弄清楚如何以升序合并两个排序的列表,但是我很难找到一种在相反方向进行合并的方法.如何将两个列表按降序合并到一个列表中而又不反转字符串呢?
I've been able to figure out how to merge two sorted lists in ascending order, but I'm having trouble finding a way to do so in the opposite direction. How can I merge the two lists into one in descending order without reversing the string after?
推荐答案
您只需要以相反的方式做所有事情-从尾部而不是头部中检索项目,进行比较时选择两者中较大的一个,并在另一个列表用尽时以相反的顺序返回其余列表:
You just have to do everything in the opposite way--retrieve items from the tail instead of the head, go for the larger of the two when making comparisons, and return the remaining list in reverse order when the other is exhausted:
def merge(lst1, lst2):
if not lst1:
return lst2[::-1]
if not lst2:
return lst1[::-1]
if lst1[-1] < lst2[-1]:
return [lst2[-1]] + merge(lst1, lst2[:-1])
else:
return [lst1[-1]] + merge(lst1[:-1], lst2)
这样:
merge([2,5,9,12], [0,1,3,4,8])
将返回:
[12, 9, 8, 5, 4, 3, 2, 1, 0]
这篇关于将两个排序列表以降序合并为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!