我们有班班:
class Shift:
def __init__(self, station, week, dayofweek, date):
self.station = station
self.week = week
self.dayofweek = dayofweek
self.date = date
,我们从该类有一个实例的排序列表(按这些转变的“日期”)。我想将具有连续日期的那些班次归为一组,并将这些组存储在末尾的列表中。
输入:
[Shift(date=1),Shift(date=2),Shift(date=4),Shift(date=5),Shift(date=6)]
输出:[[Shift(date=1),Shift(date=2)],[Shift(date=4),Shift(date=5),Shift(date=6)]]
答案 0 :(得分:1)
您需要跟踪最后看到的Shift
,然后决定是将下一个添加到最后一个组还是开始一个新组。这是一个配对的版本:
class Shift:
def __init__(self, date):
self.date = date
# some helpers to make other code clearer
# and direct comparisons possible
def __repr__(self):
return f"Shift({self.date})"
def __lt__(self, other):
return self.date < other.date
def __sub__(self, other):
return self.date - other.date
l = [Shift(1),Shift(6),Shift(5),Shift(4),Shift(2),Shift(9),Shift(7), Shift(0)]
def groupNear(l):
if not l:
return l
group = []
current = l[0]
for s in sorted(l):
if s - current <= 1:
group.append(s)
else:
yield group
group = [s]
current = s
yield group
list(groupNear(l))
输出:
[[Shift(0), Shift(1), Shift(2)],
[Shift(4), Shift(5), Shift(6), Shift(7)],
[Shift(9)]]