0

这是我一直在尝试的片段:

>>> L1 = [i for i in range(10) if i % 2 == 0]
>>> L2 = [j for j in range(10) if j % 2]

>>> import heapq
>>> [k for k in heapq.merge(L1, L2)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> [k for k in heapq.merge(L1, L2, reverse=True)]
[1, 3, 5, 7, 9, 0, 2, 4, 6, 8]

我期待[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]是因为reverse=True。我究竟做错了什么?

4

1 回答 1

0

感谢@Thierry Lathuille的评论。我想到了。不过,它是一个非常圆的方式。

>>> L1 = [i for i in range(10) if i % 2 == 0]
>>> L2 = [j for j in range(10) if j % 2]
>>> M = [k for k in heapq.merge(sorted(L1, reverse=True), sorted(L2, reverse=True), reverse=True)]
>>> M
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

对于合并 2 个按升序排序但输出应按降序排列的列表,这似乎要简单得多:

>>> sorted(L1 + L2, reverse=True)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
于 2020-10-14T20:39:57.567 回答