我有一個元組列表,其中每個元組都是(start-time, end-time)
。我正在嘗試合併所有重疊的時間範圍並返回不同時間範圍的列表。 例如合併具有重疊時間範圍的時間範圍元組列表
[(1, 5), (2, 4), (3, 6)] ---> [(1,6)]
[(1, 3), (2, 4), (5, 8)] ---> [(1, 4), (5,8)]
這是我如何實現它。
# Algorithm
# initialranges: [(a,b), (c,d), (e,f), ...]
# First we sort each tuple then whole list.
# This will ensure that a<b, c<d, e<f ... and a < c < e ...
# BUT the order of b, d, f ... is still random
# Now we have only 3 possibilities
#================================================
# b<c<d: a-------b Ans: [(a,b),(c,d)]
# c---d
# c<=b<d: a-------b Ans: [(a,d)]
# c---d
# c<d<b: a-------b Ans: [(a,b)]
# c---d
#================================================
def mergeoverlapping(initialranges):
i = sorted(set([tuple(sorted(x)) for x in initialranges]))
# initialize final ranges to [(a,b)]
f = [i[0]]
for c, d in i[1:]:
a, b = f[-1]
if c<=b<d:
f[-1] = a, d
elif b<c<d:
f.append((c,d))
else:
# else case included for clarity. Since
# we already sorted the tuples and the list
# only remaining possibility is c<d<b
# in which case we can silently pass
pass
return f
我想如果
- 弄清楚的是一個在某些Python模塊的內置功能,可以更有效地做到這一點?或
- 是否有一種更爲pythonic的方式來實現相同的目標?
您的幫助表示感謝。謝謝!然後
謝謝!同意我應該消除`set()`。循環會照顧它。就像根據需要產生元組而不是追加到列表一樣。 – 2011-04-15 19:22:31
不幸的是,如果`len(times)== 0`,這會失敗。 – phihag 2012-05-28 21:19:38