, key value = , Python datetime lambda d: datetime.strptime(d, '%m/%Y'), L
>>> from datetime import datetime
>>> sorted(L, key = lambda d: datetime.strptime(d, '%m/%Y'))
['1/2013', '2/2013', '3/2013', '7/2013', '10/2013',
'11/2013', '12/2013', '1/2014', '2/2014', '4/2014']
" /" " ", script ( ), L, ( ):
def is_cm(d1, d2):
""" is consecutive month pair?
: Assumption d1 is older day date than d2
"""
d1 = datetime.strptime(d1, '%m/%Y')
d2 = datetime.strptime(d2, '%m/%Y')
y1, y2 = d1.year, d2.year
m1, m2 = d1.month, d2.month
if y1 == y2:
return (m2 - m1) == 1
elif (y2 - y1) == 1:
return (m1 == 12 and m2 == 1)
:
>>> is_cm('1/2012', '2/2012')
True
>>> is_cm('12/2012', '1/2013')
True
>>> is_cm('1/2015', '12/2012')
>>> is_cm('12/2012', '2/2013')
False
:
def result(dl):
"""
dl: dates list - a iterator of 'month/year' strings
type: list of strings
returns: list of lists of strings
"""
s_dl = sorted(dl, key=lambda d: datetime.strptime(d, '%m/%Y'))
r_dl = []
t_dl = [s_dl[0]]
for d in s_dl[1:]:
if not is_cm(t_dl[-1], d):
r_dl.append(t_dl)
t_dl = [d]
else:
t_dl.append(d)
return r_dl
result(L)
from datetime import datetime, , , , .
@9000 , script check @codepad.