在 Python 中组合两个排序列表 [英] Combining two sorted lists in Python
问题描述
我有两个对象列表.每个列表都已按日期时间类型的对象的属性排序.我想将两个列表合并为一个排序列表.只是进行排序的最佳方法还是在 Python 中执行此操作的更智能方法?
人们似乎把这个问题复杂化了.. 只需合并两个列表,然后对它们进行排序:
<预><代码>>>>l1 = [1, 3, 4, 7]>>>l2 = [0, 2, 5, 6, 8, 9]>>>l1.extend(l2)>>>排序(l1)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]..或更短(并且不修改l1
):
...容易!另外,它只使用两个内置函数,因此假设列表的大小合理,它应该比在循环中实现排序/合并更快.更重要的是,上面的代码少了很多,而且可读性很强.
如果您的列表很大(我猜会超过几十万),使用替代/自定义排序方法可能会更快,但可能首先要进行其他优化(例如,不存储数百万个<代码>日期时间代码>对象)
使用 timeit.Timer().repeat()
(重复函数 1000000 次),我粗略地将它与 ghoseb 的 解决方案,sorted(l1+l2)
明显更快:
merge_sorted_lists
花了..
[9.7439379692077637, 9.8844599723815918, 9.552299976348877]
sorted(l1+l2)
花了..
[2.860386848449707, 2.7589840888977051, 2.7682540416717529]
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]
..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.
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)
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
took..
[9.7439379692077637, 9.8844599723815918, 9.552299976348877]
sorted(l1+l2)
took..
[2.860386848449707, 2.7589840888977051, 2.7682540416717529]
这篇关于在 Python 中组合两个排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!