循环遍历列表中除最后一项之外的每一项,并将其与下一项进行比较。如果第二个项目的月份比第一个项目的月份正好大 1,或者如果第二个项目的月份是 1 并且第二个项目的年份比第一个项目的年份正好大 1,则两个项目是连续的。返回False
第一次失败时,否则返回True
在最后。
编辑:在第二种情况下,显然第一个月份必须是 12,此外第二个月份是 1。代码已更新。
编辑2:在第一种情况下,显然年份应该相同。这就是你写得太快所得到的结果。
例如:
#!/usr/bin/python
from datetime import date
def is_consecutive(datelist):
for idx, my_date in enumerate(datelist[:-1]):
if ((datelist[idx + 1].month - my_date.month == 1 and
datelist[idx + 1].year == my_date.year) or
(datelist[idx + 1].month == 1 and
my_date.month == 12 and
datelist[idx + 1].year - my_date.year == 1)):
continue
else:
return False
return True
print is_consecutive([date(2010, 10, 3),
date(2010, 11, 8),
date(2010, 12, 1),
date(2011, 1, 11)])
print is_consecutive([date(2010, 7, 6),
date(2010, 8, 24),
date(2010, 3, 5),
date(2010, 10, 25)])
另一种实现,可能更容易遵循,但基本上做同样的事情:
def is_consecutive(datelist):
for idx, my_date in enumerate(datelist[:-1]):
month_diff = datelist[idx + 1].month - my_date.month
year_diff = datelist[idx + 1].year - my_date.year
if ((month_diff == 1 and year_diff == 0) or
(month_diff == -11 and year_diff == 1)):
continue
else:
return False
return True