排序和合并两个列表列表

时间:2012-09-17 10:07:12

标签: python

我有两个清单,

[[1, 2], [4, 7], [11, 13], [15, 21]]

[[3, 4], [5,12], [23, 25]]

我想要这样的输出。

[[1, 2], [3,13], [15, 21], [23, 25]]

任何人都可以帮助我?

1 个答案:

答案 0 :(得分:5)

来自Merging a list of time-range tuples that have overlapping time-ranges的算法非常适合您的输入,只要您将它们连接起来:

def merge(times):
    saved = list(times[0])
    for st, en in sorted([sorted(t) for t in times]):
        if st <= saved[1]:
            saved[1] = max(saved[1], en)
        else:
            yield tuple(saved)
            saved[0] = st
            saved[1] = en
    yield tuple(saved)

lst1 = [[1, 2], [4, 7], [11, 13], [15, 21]]
lst2 = [[3, 4], [5,12], [23, 25]]

print list(merge(sorted(lst1 + lst2)))

输出:

[(1, 2), (3, 13), (15, 21), (23, 25)]