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

``````
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)

``````

``````
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)]

# ]

``````