python - 如何根据连续属性对类的对象进行分组?
问题描述
我们有一个班班:
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)]]
解决方案
您需要跟踪上次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)]]
推荐阅读
- sql - PostgreSQL - 按左连接的一对多字段排序查询结果
- java - 无法使私有广播方法起作用
- java - JavaFX_TableView_如果使用哈希图,如何为某个单元格填充颜色
- javascript - 从文本框向 D3 SVG 添加节点
- asp.net-core - EF Core 迁移错误:“无法创建 'ApplicationContext' 类型的对象”
- java - 使用选项卡和片段处理导航项
- json - UITableView 的节作为来自 Json 数据的日期
- git - Git 混淆(“更新”和“拉取”)
- android-studio - 将 gradle 链接到 android mk 文件的 Android Studio 问题
- c# - 如何在 Web 浏览器 C# 中将事件单击添加到 div