我的主題是輕微的變化(我最初建的開始/結束列表,並拉上他們返回記錄,但我更喜歡@Karl Knechtel的產生辦法):
from datetime import date, timedelta
ONE_DAY = timedelta(days=1)
def find_date_windows(dates):
# guard against getting empty list
if not dates:
return
# convert strings to sorted list of datetime.dates
dates = sorted(date(*map(int,d.split('-'))) for d in dates)
# build list of window starts and matching ends
lastStart = lastEnd = dates[0]
for d in dates[1:]:
if d-lastEnd > ONE_DAY:
yield {'start_date':lastStart, 'end_date':lastEnd}
lastStart = d
lastEnd = d
yield {'start_date':lastStart, 'end_date':lastEnd}
下面是測試情況:
tests = [
['2011-02-27', '2011-02-28', '2011-03-01', '2011-04-12', '2011-04-13', '2011-06-08'],
['2011-06-08'],
[],
['2011-02-27', '2011-02-28', '2011-03-01', '2011-04-12', '2011-04-13', '2011-06-08', '2011-06-10'],
]
for dates in tests:
print dates
for window in find_date_windows(dates):
print window
print
打印:
['2011-02-27', '2011-02-28', '2011-03-01', '2011-04-12', '2011-04-13', '2011-06-08']
{'start_date': datetime.date(2011, 2, 27), 'end_date': datetime.date(2011, 3, 1)}
{'start_date': datetime.date(2011, 4, 12), 'end_date': datetime.date(2011, 4, 13)}
{'start_date': datetime.date(2011, 6, 8), 'end_date': datetime.date(2011, 6, 8)}
['2011-06-08']
{'start_date': datetime.date(2011, 6, 8), 'end_date': datetime.date(2011, 6, 8)}
[]
['2011-02-27', '2011-02-28', '2011-03-01', '2011-04-12', '2011-04-13', '2011-06-08', '2011-06-10']
{'start_date': datetime.date(2011, 2, 27), 'end_date': datetime.date(2011, 3, 1)}
{'start_date': datetime.date(2011, 4, 12), 'end_date': datetime.date(2011, 4, 13)}
{'start_date': datetime.date(2011, 6, 8), 'end_date': datetime.date(2011, 6, 8)}
{'start_date': datetime.date(2011, 6, 10), 'end_date': datetime.date(2011, 6, 10)}
我甚至不確定你的例子中你的派生解決方案。 '2011-02-28'約會去了哪裏? – user37078
'2011-02-28'在範圍內{「start_date」:'2011-02-27','end_date':'2011-03-01'} – Continuation
好的,所以你的第二個代碼塊,dicts列表你有,不是*答案*,而只是第二個參數?如果是這樣,你可以發佈結果,因爲你期望它被返回? – user37078