如果您只想对列表进行排序,请使用 sorted 函数并传递 key 值 = 将日期字符串转换为 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'] # indented by hand
要将“月/年字符串列表”拆分为“连续月份列表列表”,您可以使用以下脚本(读取 cmets),其中,我首先对列表L 进行排序,然后在基础上对字符串进行分组连续月份(检查连续月份我写了一个函数):
def is_cm(d1, d2):
""" is consecutive month pair?
: Assumption d1 is older day's 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: # if years are same d2 should be in next month
return (m2 - m1) == 1
elif (y2 - y1) == 1: # if years are consecutive
return (m1 == 12 and m2 == 1)
它的工作原理如下:
>>> is_cm('1/2012', '2/2012')
True # yes, consecutive
>>> is_cm('12/2012', '1/2013')
True # yes, consecutive
>>> is_cm('1/2015', '12/2012') # None --> # not consecutive
>>> is_cm('12/2012', '2/2013')
False # not consecutive
拆分代码的代码:
def result(dl):
"""
dl: dates list - a iterator of 'month/year' strings
type: list of strings
returns: list of lists of strings
"""
#Sort list:
s_dl = sorted(dl, key=lambda d: datetime.strptime(d, '%m/%Y'))
r_dl = [] # list to be return
# split list into list of lists
t_dl = [s_dl[0]] # temp list
for d in s_dl[1:]:
if not is_cm(t_dl[-1], d): # check if months are not consecutive
r_dl.append(t_dl)
t_dl = [d]
else:
t_dl.append(d)
return r_dl
result(L)
不要忘记包含from datetime import datetime,这个技巧我相信你可以很容易地更新一个新的日期列表,其中日期是其他格式的。
在@9000 提示之后,如果您想检查旧脚本检查@codepad,我可以简化我的排序函数并删除旧答案。