datetime - 日期日期 - 对连续元素进行分组

给出了一个列表:A= [datetime.datetime(2019 ,12 ,14 ,0 ,0) ,datetime.datetime(2019 ,12 ,24 ,0 ,0) ,datetime.datetime(2019 ,12 ,25 ,0 ,0) ,datetime.datetime(2019 ,12 ,26 ,0 ,0) ,datetime.datetime(2019 ,12 ,27 ,0 ,0) ,datetime.datetime(2019 ,12 ,28 ,0 ,0) ,datetime.datetime(2019 ,12 ,29 ,0 ,0) ,datetime.datetime(2019 ,12 ,30 ,0 ,0) ,datetime.datetime(2019 ,12 ,31 ,0 ,0)] i want to have elements whose difference is 1 and group them so that the o/p is [datetime.datetime(2019 ,12 ,14 ,0 ,0) ,[datetime.datetime(2019 ,12 ,24 ,0 ,0) ,datetime.datetime(2019 ,12 ,25 ,0 ,0) ,datetime.datetime(2019 ,12 ,26 ,0 ,0) ,datetime.datetime(2019 ,12 ,27 ,0 ,0) ,datetime.datetime(2019 ,12 ,28 ,0 ,0) ,datetime.datetime(2019 ,12 ,29 ,0 ,0) ,datetime.datetime(2019 ,12 ,30 ,0 ,0) ,datetime.datetime(2019 ,12 ,31 ,0 ,0)] ] 但是失败了,谁能帮我?


res = []


temp = []


l = len(A)-1


for i,v in enumerate(A):


 if i+1 > l:


 break



 if abs(v.days() - A[i+1].days()) == 1:


 temp.append(v)


 else:


 if temp:


 temp.append(v)


 res.append(temp)


 temp = []


print(res)



时间:

你可以使用itertools.groupbyitertools.count像这样对它们进行分组:


from itertools import groupby, count



counter = count()


A= [1,14,24,25,26,27,28,29,30,31]


out = [list(group) for _, group in groupby(A, key=lambda v:v-next(counter))]


print(out)


# [[1], [14], [24, 25, 26, 27, 28, 29, 30, 31]]



如果你真的希望孤立值出现在列表中,只需添加:


out = [sublist[0] if len(sublist)==1 else sublist for sublist in out]


print(out)


[1, 14, [24, 25, 26, 27, 28, 29, 30, 31]]



next(counter)将返回0,1,2,所以每次被称为,如果值之间的差异为1,则v-next(counter)将是常数,而且将这些项保持为常数。

datetime.timedelta(days=next(counter))而不是next(counter)


from itertools import groupby, count


import datetime



A = [datetime.datetime(2019, 12, 14, 0, 0), datetime.datetime(2019, 12, 24, 0, 0), 


 datetime.datetime(2019, 12, 25, 0, 0), datetime.datetime(2019, 12, 26, 0, 0), 


 datetime.datetime(2019, 12, 27, 0, 0), datetime.datetime(2019, 12, 28, 0, 0), 


 datetime.datetime(2019, 12, 29, 0, 0), datetime.datetime(2019, 12, 30, 0, 0), 


 datetime.datetime(2019, 12, 31, 0, 0)] 



counter = count() 



out = [list(group) for _, group in groupby(A, key=lambda v:v-datetime.timedelta(days=next(counter)))]



# print(out)


# [1], [14], [24, 25, 26, 27, 28, 29, 30, 31]]



out = [sublist[0] if len(sublist)==1 else sublist for sublist in out]


print(out)



# [datetime.datetime(2019, 12, 14, 0, 0), 


# [datetime.datetime(2019, 12, 24, 0, 0), datetime.datetime(2019, 12, 25, 0, 0),..., datetime.datetime(2019, 12, 31, 0, 0)]


# ]



...