0

Starting with some lists of tuples.

a = [(10,10),(20,20)]
b = [(15,15),(25,25)]

What list comprehension can we use to create a new list, where the items from a, b is in order of size?

c = [(10,10),(15,15),(20,20),(25,25)]
4

5 回答 5

10

你不需要理解这一点,你可以简单地做:

c = a + b
c.sort()
>> [(10, 10), (15, 15), (20, 20), (25, 25)]

甚至更短:

c = sorted(a + b)
>> [(10, 10), (15, 15), (20, 20), (25, 25)]
于 2013-04-29T13:39:37.590 回答
5

如果两个列表都已排序...

c = list(heapq.merge(a, b))

否则

c = sorted(itertools.chain(a, b))
于 2013-04-29T13:43:56.057 回答
4

为什么是列表理解?我不知道您所说的“大小”是什么意思,所以我要猜测面积。

c = sorted(a+b, key=lambda x: x[0]*x[1])
于 2013-04-29T13:42:05.057 回答
2
from itertools import chain

a = [(10,10),(20,20)]
b = [(15,15),(25,25)]
sorted(chain(a, b))
# [(10, 10), (15, 15), (20, 20), (25, 25)]
于 2013-04-29T13:41:42.443 回答
1

您可能应该阅读Sorting HOWTO。特别是,关键功能部分可能是相关的,具体取决于您如何定义“大小”。

于 2013-04-29T13:41:20.787 回答