在Python中合并两个排序的列表 [英] Combining two sorted lists in Python

查看:203
本文介绍了在Python中合并两个排序的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个对象列表.每个列表已经按日期时间类型的对象的属性进行排序.我想将两个列表合并为一个排序的列表.最好的方法是仅执行某种排序,还是在Python中有更聪明的方法来做到这一点?

I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python?

推荐答案

人们似乎过于复杂了.只需组合两个列表,然后对它们进行排序:

People seem to be over complicating this.. Just combine the two lists, then sort them:

>>> l1 = [1, 3, 4, 7]
>>> l2 = [0, 2, 5, 6, 8, 9]
>>> l1.extend(l2)
>>> sorted(l1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

..或更短(且无需修改l1):

..or shorter (and without modifying l1):

>>> sorted(l1 + l2)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

..简单!另外,它仅使用两个内置函数,因此,假设列表的大小合理,则比在循环中实现排序/合并要快.更重要的是,以上代码少得多,而且可读性强.

..easy! Plus, it's using only two built-in functions, so assuming the lists are of a reasonable size, it should be quicker than implementing the sorting/merging in a loop. More importantly, the above is much less code, and very readable.

如果您的列表很大(我想可能超过几十万),则使用替代/自定义排序方法可能会更快,但是可能首先要进行其他优化(例如,不存储数百万个datetime对象)

If your lists are large (over a few hundred thousand, I would guess), it may be quicker to use an alternative/custom sorting method, but there are likely other optimisations to be made first (e.g not storing millions of datetime objects)

使用timeit.Timer().repeat()(将功能重复1000000次),我相对于

Using the timeit.Timer().repeat() (which repeats the functions 1000000 times), I loosely benchmarked it against ghoseb's solution, and sorted(l1+l2) is substantially quicker:

merge_sorted_lists接过..

[9.7439379692077637, 9.8844599723815918, 9.552299976348877]

sorted(l1+l2)接过.

[2.860386848449707, 2.7589840888977051, 2.7682540416717529]

这篇关于在Python中合并两个排序的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆