我有两个清单,
[[1, 2], [4, 7], [11, 13], [15, 21]]
[[3, 4], [5,12], [23, 25]]
我想要这样的输出。
[[1, 2], [3,13], [15, 21], [23, 25]]
任何人都可以帮助我吗?
我有两个清单,
[[1, 2], [4, 7], [11, 13], [15, 21]]
[[3, 4], [5,12], [23, 25]]
我想要这样的输出。
[[1, 2], [3,13], [15, 21], [23, 25]]
任何人都可以帮助我吗?
合并具有重叠时间范围的时间范围元组列表中的算法非常适合您的输入,前提是您将它们连接起来:
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)]